Module: Imsticker

Defined in:
lib/imsticker.rb,
lib/imsticker/version.rb

Constant Summary collapse

VERSION =
"0.1.7"

Class Method Summary collapse

Class Method Details

.download_template(tmp_dir, template_dir) ⇒ Object



226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/imsticker.rb', line 226

def self.download_template(tmp_dir, template_dir)
  puts 'No templates. Downloading ...'
  if File.exist?(template_dir)
    FileUtils.rm_rf template_dir
  end
  parent = Pathname.new(template_dir).parent()
  if File.exist?(parent)
    FileUtils.rm_rf File.join(parent, 'iOStickersTemplate-master')
  end
  open('https://github.com/nicnocquee/iOStickersTemplate/archive/master.zip') {|f|
    master_zip = File.join(tmp_dir, "master.zip")
    File.open(master_zip,"wb") do |file|
      file.puts f.read
      puts 'Extracting sticker template ...'
      Zip::File.open(master_zip) do |zip_file|
        zip_file.each do |entry|
          # puts "\tExtracting #{entry.name}"
          dest_file = File.join(tmp_dir, entry.name)
          entry.extract(dest_file)
        end
        File.rename(File.join(tmp_dir, 'iOStickersTemplate-master'), template_dir)
        puts "Template downloaded."
        File.delete(master_zip)
      end
    end
  }
end

.generateObject



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/imsticker.rb', line 10

def self.generate
  info_message
  # check if info.json exists
  if File.exist?("info.json") == false
    raise "Where is your info.json file? Create it by running `imsticker init`"
  end
  if Dir.exist?('stickers') == false
    raise "Cannot find `stickers` directory in current directory."
  end

  # check if have downloaded template
  # if yes, check version. if new version exists, download new template
  # if no, download template
  tmp_dir = File.join(Dir.home, ".imsticker")
  if Dir.exist?(tmp_dir) == false
    Dir.mkdir(tmp_dir)
  end

  template_dir = File.join(tmp_dir, 'template')
  version_file = File.join(template_dir, 'version')
  if File.exist?(version_file) == false
    download_template(tmp_dir, template_dir)
  else
    downloaded_version = File.read(version_file)
    puts "Current template version: #{downloaded_version}"
    recent_version = downloaded_version
    open('https://raw.githubusercontent.com/nicnocquee/iOStickersTemplate/master/version') {|f|
      recent_version = f.read
    }
    puts "Online version #{recent_version}"
    if downloaded_version != recent_version
      puts "New template version available. Downloading ..."
      download_template(tmp_dir, template_dir)
    end
  end

  # copy the template to temp directory
  proj_tmp_dir = Dir.mktmpdir
  FileUtils.cp_r template_dir, proj_tmp_dir
  proj_tmp_dir = File.join(proj_tmp_dir, 'template')

  # read info file
  info = JSON.parse(File.read('./info.json'))
  info['name'] = "#{info['name'].split.map(&:capitalize)*' '}"

  # list files in stickers folder. single file = single sticker image, a folder = sticker sequence
  supported_exts = ['png', 'apng', 'gif', 'jpeg', 'jpg']
  supported_files = File.join(File.join('.', 'stickers'), "*.{#{supported_exts.join(',')}}")

  sticker_target_directory = File.join(File.join(File.join(proj_tmp_dir, 'StickerPackExtension'), 'Stickers.xcstickers'), "Sticker Pack.stickerpack")
  sticker_contents_json = {
    'info' => {
      'version' => 1,
      'author' => 'xcode'
    },
    'properties' => {
      'filename' => ''
    }
  }
  sticker_sequence_contents_json = {
    'info' => {
      'version' => 1,
      'author' => 'xcode'
    },
    'properties' => {
      "duration" => 15,
      "duration-type" => "fps",
      "repetitions" => 0
    },
    'frames' => []
  }
  stickers_contents_json_file = File.join(sticker_target_directory, 'Contents.json')
  stickers_contents_json = JSON.parse(File.read(stickers_contents_json_file))

  # create a directory in Sticker Pack.stickerpack directory for each of the stickers. e.g., file_name.sticker, file_name.stickersequence
  puts "Reading stickers directory ..."
  number_of_stickers = 0
  Dir.entries('stickers').select {|entry|
    if entry != '.' && entry != '..'
      file = File.join('stickers', entry)
      ext_with_period = File.extname(file)
      file_name_without_ext = File.basename(file, ext_with_period)
      ext = ext_with_period.downcase.strip.split('.').last
      sticker_entry = ''
      # if single sticker, write Contents.json in it with content following Contents-sticker.json, copy the image file to the directory.
      if supported_exts.include?(ext)
        number_of_stickers += 1
        puts "  Found #{entry} sticker"
        sticker_entry = "#{file_name_without_ext}.sticker"
        sticker_dir = File.join(sticker_target_directory, sticker_entry)
        Dir.mkdir(sticker_dir)
        FileUtils.cp(file, File.join(sticker_dir, entry))
        sticker_contents_json['properties']['filename'] = entry
        json = JSON.generate(sticker_contents_json)
        File.open(File.join(sticker_dir, 'Contents.json'), "w") {|f|
          f.write(json)
        }
      end

      # if stickersequence, write Contents.json in it with content following Contents-stickersequence.json, copy the images files to the dir.
      if File.directory?(file)
        puts "  Found #{entry} sticker sequence"
        number_of_stickers += 1
        sticker_entry = "#{file_name_without_ext}.stickersequence"
        sticker_dir = File.join(sticker_target_directory, sticker_entry)
        Dir.mkdir(sticker_dir)
        Dir.entries(file).sort_by {|f| File.basename(f)}.select {|f|
          if f != '.' && f != '..'
            FileUtils.cp(File.join(file, f), File.join(sticker_dir, f))
            sticker_sequence_contents_json['frames'].push({
              'filename' => f
            })
          end
        }
        json = JSON.generate(sticker_sequence_contents_json)
        File.open(File.join(sticker_dir, 'Contents.json'), "w") {|f|
          f.write(json)
        }
      end

      # add `stickers` key in Sticker Pack.stickerpack/Contents.json with value an array of dictionaries: { "filename": "stickername.sticker" }
      if sticker_entry != ''
        stickers_contents_json['stickers'].push({
            'filename' => sticker_entry
        })
      end
    end

    # write Sticker Pack.stickerpack/Contents.json
    json = JSON.generate(stickers_contents_json)
    File.open(stickers_contents_json_file, "w") {|f|
        f.write(json)
    }
  }

  puts "Processed #{number_of_stickers} stickers."

  # check if user provides icons
  rectangle_icon = 'icon1024x768.png'
  icons_directory = File.join(File.join(File.join(proj_tmp_dir, 'StickerPackExtension'), 'Stickers.xcstickers'), "iMessage App Icon.stickersiconset")
  if File.exist?(rectangle_icon)
    puts "Found icon. Creating icons ..."
    processor = ImageResizer::Processor.new
    sizes = ['32x24', '27x20', '60x45', '74x55', '67x50']
    sizes.each {|size|
      width = size.split('x')[0].to_i
      height = size.split('x')[1].to_i
      [1, 2, 3].each {|scale|
        scale_string = ( scale > 1 ) ? "@#{scale}x.png" : ".png"
        filename = "#{size}#{scale_string}"
        image = ImageResizer::TempObject.new(File.new(rectangle_icon))
        tempfile = processor.resize(image, :width => scale * width, :height => scale * height)
        File.open(File.join(icons_directory, filename), 'wb') { |f| f.write(File.read(tempfile)) }
      }
    }
    square_sizes = ['29x29']
    crop_length = ((1024.0-768.0)/2.0)/1024.0
    square_sizes.each {|size|
      width = size.split('x')[0].to_i
      upper_left = [crop_length, 0]
      lower_right = [1-crop_length, 1]
      [1, 2, 3].each {|scale|
        scale_string = ( scale > 1 ) ? "@#{scale}x.png" : ".png"
        filename = "#{size}#{scale_string}"
        image = ImageResizer::TempObject.new(File.new(rectangle_icon))
        tempfile = processor.crop_to_frame_and_resize(image,
                                          :upper_left => upper_left,
                                          :lower_right => lower_right,
                                          :width => scale * width
                                          )
        File.open(File.join(icons_directory, filename), 'wb') { |f| f.write(File.read(tempfile)) }

        # ipad 2x
        if scale == 2
          filename2 = "#{size}@#{scale}x-1.png"
          File.open(File.join(icons_directory, filename2), 'wb') { |f| f.write(File.read(tempfile)) }
        end
      }
    }
  else
    puts "Cannot find `icon1024x768.png`. Add `icon1024x768.png` to automate icons creation."
  end

  # cp the app store image
  FileUtils.cp rectangle_icon, File.join(icons_directory, "#{info['name']}.png")

  # copy the modified template to output directory
  puts "Writing project to output directory ..."
  FileUtils.rm_rf './output'
  FileUtils.cp_r proj_tmp_dir, './output'

  # Rename project
  puts "Renaming project name ..."
  xcodeproj = File.join('./output', 'Awesome Stickers.xcodeproj')
  new_xcodeproj = File.join('./output', "#{info['name']}.xcodeproj")
  pbxproj = File.join(xcodeproj, 'project.pbxproj')
  new_pbxproj = File.read(pbxproj).gsub('Awesome Stickers', info['name'])
  xcworkspacedata = File.join(File.join(xcodeproj, 'project.xcworkspace'), 'contents.xcworkspacedata')
  new_xcworkspacedata = File.read(xcworkspacedata).gsub('Awesome Stickers', info['name'])
  File.open(pbxproj, 'wb') {|f| f.write(new_pbxproj)}
  File.open(xcworkspacedata, 'wb') {|f| f.write(new_xcworkspacedata)}
  File.rename xcodeproj, new_xcodeproj

  info_plist = File.join(File.join('./output', 'TestStickers'), 'Info.plist')
  info_plist_content = File.read(info_plist)
  new_info_plist_content = info_plist_content.gsub('Awesome Stickers', info['name'])
  File.open(info_plist, 'wb') {|f| f.write(new_info_plist_content)}

  info_plist = File.join(File.join('./output', 'StickerPackExtension'), 'Info.plist')
  info_plist_content = File.read(info_plist)
  new_info_plist_content = info_plist_content.gsub('Awesome Stickers', info['name'])
  File.open(info_plist, 'wb') {|f| f.write(new_info_plist_content)}

  puts "Done. Now you can open file \"output/#{info['name']}.xcodeproj\" and run it in the simulator."
end

.info_messageObject



254
255
256
257
258
259
260
261
262
# File 'lib/imsticker.rb', line 254

def self.info_message
  puts ""
  puts ""
  puts "================================"
  puts "imsticker v#{Imsticker::VERSION}"
  puts "================================"
  puts ""
  puts ""
end

.initObject



264
265
266
267
268
269
270
271
272
273
274
275
# File 'lib/imsticker.rb', line 264

def self.init
  info_message
  info = {
    "name" => "Awesome stickers",
    "website" => "http://delightfuldev.com"
  }
  json = JSON.pretty_generate(info)
  File.open('info.json', "w") {|f|
      f.write(json)
  }
  puts "Created `info.json` in current directory. Edit it to your liking."
end