forked from magicpriest/moo-indesign
-
Notifications
You must be signed in to change notification settings - Fork 0
/
moo.jsx
2988 lines (2598 loc) · 105 KB
/
moo.jsx
1
2
3
4
5
6
7
8
9
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
225
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//---------------------------------------------------------*- javascript -*----
//
// moo.jsx
//
// an InDesign script to assist in the creation of MOO Business Cards
//
// (c) MOO Print Ltd 2012
//
//-----------------------------------------------------------------------------
//
// includes the following third-party libraries (see below for licences):
//
// OAuth (c) Netflix, Inc. 2008
// SHA (c) Brian Turek 2008-2010
// JSON Douglas Crockford (Public Domain)
//
//-----------------------------------------------------------------------------
#target indesign
#targetengine 'session'
(function() {
var API_HOST = 'uk.moo.com';
var API_KEY = 'a688570817ce61d49cebd98b933acec604f8834a1';
var API_SECRET = '24bd1fc5e812b8412a6ffd787867fd3e';
var USER_AGENT = 'MOO InDesign ExtendScript';
var SIDE_TYPES = {details: {name: 'Details', prefix: 'D'},
image: {name: 'Image', prefix: 'I'}};
var ORIENTATIONS = {landscape: {name: 'Landscape', code: PageOrientation.landscape},
portrait: {name: 'Portrait', code: PageOrientation.portrait}};
var SIZES = [{name: "Business Card",
mooName: "businesscard",
templates: {details: {landscape: {code: "businesscard_full_details_image_landscape",
linkId: 'variable_image_back'},
portrait: {code: "businesscard_full_details_image_portrait",
linkId: 'variable_image_back'}},
image: {landscape: {code: "businesscard_full_image_landscape",
linkId: 'variable_image_front'},
portrait: {code: "businesscard_full_image_portrait",
linkId: 'variable_image_front'}}},
width: 84, //mm
height: 55, //mm
items: 50
},
{name: "MiniCard",
mooName: "minicard",
templates: {details: {landscape: {code: "minicard_full_details_image_landscape",
linkId: 'variable_image_back'},
portrait: {code: "minicard_full_details_image_portrait",
linkId: 'variable_image_back'}},
image: {landscape: {code: "minicard_full_image_landscape",
linkId: 'variable_image_front'},
portrait: {code: "minicard_full_image_portrait",
linkId: 'variable_image_front'}}},
width: 70, //mm
height: 28, //mm
items: 100
},
{name: "Postcard",
mooName: "postcard",
templates: {details: {landscape: {code: "postcard_full_details_image_landscape",
linkId: 'variable_image_back'},
portrait: {code: "postcard_full_details_image_portrait",
linkId: 'variable_image_back'}},
image: {landscape: {code: "postcard_full_image_landscape",
linkId: 'variable_image_front'},
portrait: {code: "postcard_full_image_portrait",
linkId: 'variable_image_front'}}},
width: 148, //mm
height: 105, //mm
items: 10
}];
var BLEED = 2; //mm
var MARGIN = 2; //mm
var SLUG = 8; //mm
var PDF_EXPORT_PRESET = {
name: "MOO",
bleedTop: BLEED + "mm",
bleedBottom: BLEED + "mm",
bleedInside: BLEED + "mm",
bleedOutside: BLEED + "mm",
bleedMarks: false,
colorBitmapCompression: BitmapCompression.NONE,
colorBitmapSampling: Sampling.NONE,
cropMarks: false,
exportGuidesAndGrids: false,
exportLayers: false,
exportNonprintingObjects: false,
generateThumbnails: false,
grayscaleBitmapCompression: BitmapCompression.NONE,
grayscaleBitmapSampling: Sampling.NONE,
includeSlugWithPDF: false,
monochromeBitmapCompression: BitmapCompression.NONE,
monochromeBitmapSampling: Sampling.NONE,
optimizePDF: false,
pageInformationMarks: false,
standardsCompliance: PDFXStandards.PDFX1A2003_STANDARD,
useDocumentBleedWithPDF: true
};
function documentPresetForSizeAndOrientation(size, orientation) {
return {
name: orientation.name + ' ' + size.name,
pageHeight: size.height + "mm",
pageWidth: size.width + "mm",
pageOrientation: orientation.code,
intent: DocumentIntentOptions.PRINT_INTENT,
facingPages: false,
documentBleedUniformSize: true,
documentBleedTopOffset: BLEED + "mm",
top: MARGIN + "mm",
bottom: MARGIN + "mm",
left: MARGIN + "mm",
right: MARGIN + "mm",
slugTopOffset: SLUG + "mm"
};
}
function masterForSideType(document, sideType) {
// validate sideType?
var sideTypeObj = SIDE_TYPES[sideType];
var masters = document.masterSpreads;
for (var i = 0; i < masters.count(); ++ i) {
var master = masters.item(i);
if (master.baseName === sideTypeObj.name) {
return master;
}
}
// need to create master, then
var master = document.masterSpreads.add(1, {baseName: sideTypeObj.name, namePrefix: sideTypeObj.prefix});
var page = master.pages.item(0);
var measurements = pageMeasurements(page);
var textFrame = master.pages.item(0).textFrames.add();
textFrame.geometricBounds = [-document.documentPreferences.slugTopOffset, 0,
-document.documentPreferences.documentBleedTopOffset, measurements.width];
textFrame.contents = SIDE_TYPES[sideType].name + " side";
text = textFrame.texts.item(0);
text.pointSize = 10;
text.justification = Justification.centerAlign;
// place something on it
return master;
}
function setSideTypeForPage(document, page, sideType) {
page.appliedMaster = masterForSideType(document, sideType);
}
function sideTypeForPage(page) {
var master = page.appliedMaster;
if (master && master !== NothingEnum.NOTHING) {
for (var sideType in SIDE_TYPES) {
var name = SIDE_TYPES[sideType].name;
if (master.baseName === name) {
return sideType;
}
}
}
return undefined;
}
function simplePack(document, imageBasketItems, size) {
var sides = [];
var itemCount = imageBasketItems.length;
var sideTypesSeen = {};
for (var i = 0; i < itemCount; ++ i) {
var page = document.pages.item(i);
var sideType = sideTypeForPage(page); // should be valid by this point
var orientation = 'landscape';
var data = [];
var measurements = pageMeasurements(page);
orientation = measurements.width > measurements.height ? 'landscape' : 'portrait';
var w = orientation === 'landscape' ? size.width : size.height;
var h = orientation === 'landscape' ? size.height : size.width;
data = [{
type: 'imageData',
linkId: size.templates[sideType][orientation].linkId,
imageBox: {
center: {
x: w / 2 + BLEED,
y: h / 2 + BLEED
},
width: w + BLEED * 2,
height: h + BLEED * 2,
angle: 0
},
resourceUri: imageBasketItems[i].resourceUri,
enhance: false
}];
sides.push({
type: sideType,
sideNum: i + 1,
templateCode: size.templates[sideType][orientation].code,
data: data
});
sideTypesSeen[sideType] = true;
}
// need at least one of each side
for (var sideType in SIDE_TYPES) {
if (!(sideType in sideTypesSeen)) {
sides.push({
type: sideType,
sideNum: 0,
templateCode: size.templates[sideType]['landscape'].code,
data: []
});
}
}
return {
numCards: size.items,
productCode: size.mooName,
productVersion: 1,
sides: sides,
extras: [],
imageBasket: {
items: imageBasketItems
}
};
}
function pageMeasurements(page) {
var bounds = page.bounds;
var width = Math.round(bounds[3] - bounds[1]);
var height = Math.round(bounds[2] - bounds[0]);
return {width: width, height: height};
}
function pageMatchesSize(page, size) {
var measurements = pageMeasurements(page);
var matches = (measurements.width.toString() == size.width.toString() && measurements.height.toString() == size.height.toString())
|| (measurements.height.toString() == size.width.toString() && measurements.width.toString() == size.height.toString());
return matches;
}
function checkSideTypes(document) {
var ok = true;
var pageCount = document.pages.length;
for (var i = 0; i < pageCount && ok; ++ i) {
var page = document.pages.item(i);
ok = sideTypeForPage(page) in SIDE_TYPES;
}
return ok;
}
function sizeForDocument(document) {
// either returns size object or undefined
var pageCount = document.pages.length;
for (var i = 0; i < SIZES.length; ++ i) {
var size = SIZES[i];
var pageMatched = true;
for (var j = 0; j < pageCount && pageMatched; ++ j) {
pageMatched = pageMatchesSize(document.pages[j], size);
}
if (pageMatched) {
return size;
}
}
return undefined;
}
function http(host, method, path, content, contentType, progressHook) {
var request = []
if (progressHook) {
progressHook('assembling content');
}
request.push(method, ' ', path, ' ', "HTTP/1.0\n");
request.push('Host: ', host, "\n");
request.push('User-Agent: ', USER_AGENT, "\n");
request.push('Connection: ', 'close', "\n");
if (content) {
request.push('Content-Length: ', content.length, "\n");
if (contentType) {
request.push('Content-Type: ', contentType, "\n");
}
}
request.push("\n");
if (content) {
request.push(content);
}
if (progressHook) {
progressHook('sending content');
}
var socket = new Socket;
socket.timeout = 60; //?
if (!socket.open(host + ':80', 'BINARY')) {
return {error: "could not connect to " + host};
}
for (var i = 0; i < request.length; ++ i) {
socket.write(request[i]);
}
if (progressHook) {
progressHook('waiting for response');
}
var bufferSize = 1; // kb
var block = 1;
var responseArray = []
while (socket.connected && !socket.eof) {
if (progressHook) {
progressHook('reading response: ' + (block * bufferSize) + ' Kb');
}
var chars = socket.read(bufferSize * 1024);
responseArray.push(chars);
++ block;
}
socket.close();
var response = responseArray.join('');
var statusLineOffset = response.indexOf("\r\n");
var statusLine = response.substring(0, statusLineOffset);
var status = statusLine.split(' ')[1];
var bodyOffset = response.indexOf("\r\n\r\n");
var body = response.substring(bodyOffset + 4);
return {status: status, body: body};
}
function contentAndBoundaryForMultiPart(parts) {
var boundary = Math.random();
var contentArray = []
for (var i = 0; i < parts.length; ++ i) {
contentArray.push("--", boundary, "\r\n");
var part = parts[i];
if (part.value) {
contentArray.push("Content-Disposition: form-data; name=\"", part.key, "\"\r\n\r\n", part.value, "\r\n");
} else if (part.filePath) {
var file = new File(part.filePath);
file.encoding = "BINARY";
file.open("r")
var fileContents = file.read();
file.close();
contentArray.push("Content-Disposition: form-data; name=\"", part.key,
"\"; filename=\"", part.filePath, "\"\r\n",
"Content-Transfer-Encoding: binary\r\n",
"Content-Type: ", part.contentType, "\r\n\r\n",
fileContents, "\r\n");
}
}
contentArray.push("--", boundary, "--");
return {boundary: boundary, content: contentArray.join('')};
}
function uploadToMOO(filePath, progressHook) {
var parts = [
{key: 'method', value: 'moo.image.uploadImage'},
{key: 'imageFile', filePath: filePath, contentType: 'application/pdf'}
];
var contentAndBoundary = contentAndBoundaryForMultiPart(parts);
var response = http(API_HOST, 'POST', '/api/service/',
contentAndBoundary.content, "multipart/form-data; boundary=" + contentAndBoundary.boundary, progressHook);
if (response.hasOwnProperty('error') || !response.hasOwnProperty('status') || response.status != 200 || !response.hasOwnProperty('body')) {
return null;
}
var parsedResponse = JSON.parse(response.body);
if (!parsedResponse.hasOwnProperty('imageBasketItem')) {
return null;
}
return parsedResponse.imageBasketItem;
}
function createPack(product, packData, progressHook) {
var parameters = {
method: 'moo.pack.createPack',
product: product,
pack: JSON.stringify(packData)
};
var message = {
method: 'POST',
action: 'http://' + API_HOST + '/api/service/',
parameters: parameters
};
var accessor = {
token: '',
tokenSecret: '',
consumerKey: API_KEY,
consumerSecret: API_SECRET
};
OAuth.completeRequest(message, accessor);
var content = OAuth.formEncode(message.parameters);
var response = http(API_HOST, 'POST', '/api/service/', content, "application/x-www-form-urlencoded", progressHook);
if (response.hasOwnProperty('error') || !response.hasOwnProperty('status') || response.status != 200 || !response.hasOwnProperty('body')) {
return null;
}
var parsedResponse = JSON.parse(response.body);
if (!parsedResponse.hasOwnProperty('dropIns')) {
return null;
}
return parsedResponse.dropIns.preview;
}
function visit(url) {
if (File.fs == "Macintosh") {
var body = 'tell application "Finder"\ropen location "' + url + '"\rend tell';
app.doScript(body,ScriptLanguage.APPLESCRIPT_LANGUAGE);
} else {
var body = 'dim objShell\rset objShell = CreateObject("Shell.Application")\rstr = "' + url + '"\robjShell.ShellExecute str, "", "", "open", "1"';
app.doScript(body,ScriptLanguage.VISUAL_BASIC);
}
}
// Reset menu to known state
var mainMenu = app.menus.item("$ID/Main");
var fileMenu = mainMenu.menuElements.item("File");
try {
mainMenu.submenus.item("MOO").remove();
fileMenu.menuElements.item("Export for").menuElements.item("MOO...").remove();
} catch (myError) {
}
// Reset menu actions to known state
app.scriptMenuActions.everyItem().remove();
// Add menus/items
var mooMenu = mainMenu.submenus.add("MOO");
var newMenu = mooMenu.submenus.add("New");
// Add pdf export preset
try {
app.pdfExportPresets.item(PDF_EXPORT_PRESET.name).remove();
} catch (myError) {
}
app.pdfExportPresets.add(PDF_EXPORT_PRESET);
// Add document presets and script actions
for (var i = 0; i < SIZES.length; ++ i) {
var size = SIZES[i];
for (var orientation in ORIENTATIONS) {
var documentPreset = documentPresetForSizeAndOrientation(size, ORIENTATIONS[orientation]);
var documentPresetName = documentPreset.name;
try {
app.documentPresets.item(documentPresetName).remove();
} catch (myError) {
}
app.documentPresets.add(documentPreset);
var action = app.scriptMenuActions.add(documentPresetName);
action.addEventListener('onInvoke', (function(documentPresetName, size) {
return function() {
var document = app.documents.add(true, app.documentPresets.item(documentPresetName));
document.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.MILLIMETERS;
document.viewPreferences.verticalMeasurementUnits = MeasurementUnits.MILLIMETERS;
for (var sideType in SIDE_TYPES) {
masterForSideType(document, sideType);
}
try {
document.masterSpreads.itemByName('A-Master').remove();
} catch (myError) {
}
setSideTypeForPage(document, document.pages.item(0), 'details');
app.activeWindow.activePage = document.pages.item(0); // make the first 'real' page the activePage
};
})(documentPresetName, size));
newMenu.menuItems.add(action);
}
}
var addPageAction = function addPageAction(sideType) {
return function() {
try {
var document = app.activeDocument;
} catch (myError) {
alert('Please select a document and try again.');
return;
}
var size = sizeForDocument(document);
if (size === undefined) {
alert("This document isn't the right shape or size for MOO. Sorry!");
return;
}
var page = document.pages.add();
setSideTypeForPage(document, page, sideType);
}
};
var changePageAction = function changePageAction(sideType) {
return function() {
try {
var document = app.activeDocument;
} catch (myError) {
alert('Please select a document and try again.');
return;
}
var size = sizeForDocument(document);
if (size === undefined) {
alert("This document isn't the right shape or size for MOO. Sorry!");
return;
}
var page = null;
try {
var page = app.activeWindow.activePage;
} catch (myError) {
alert('Please select a page and try again.');
return;
}
setSideTypeForPage(document, page, sideType);
}
};
var uploadAction = function() {
try {
var document = app.activeDocument;
} catch (myError) {
alert('Please select a document and try again.');
return;
}
var size = sizeForDocument(document);
if (size === undefined) {
alert("This document isn't the right shape or size for MOO. Sorry!");
return;
}
if (!checkSideTypes(document)) {
alert("Sorry, all sides must be 'details' or 'image' before this document can be sent to MOO.");
return;
}
// (Re-)Add pdf export preset
try {
app.pdfExportPresets.item(PDF_EXPORT_PRESET.name).remove();
} catch (myError) {
alert("We can't install the correct PDF export settings!");
return;
}
var now = new Date().getTime();
app.pdfExportPresets.add(PDF_EXPORT_PRESET);
var progressPanel = Window.find('palette', 'MOO');
if (progressPanel === null) {
progressPanel = new Window('palette', 'MOO');
progressPanel.add('statictext', [0, 0, 320, 24], "Validating document",
{name: 'progressStatus'});
}
var progressStatus = progressPanel.findElement('progressStatus');
progressPanel.show();
try {
var imageBasketItems = [];
for (var i = 0; i < document.pages.length; ++ i) {
var pageName = document.pages.item(i).name;
pageName = pageName.replace(new RegExp(":","gi"), "_");
progressStatus.text = "Exporting PDF for side " + (i + 1);
progressPanel.update();
app.pdfExportPreferences.pageRange = pageName;
var file = undefined;
try {
var filePath = Folder.temp + "/moo-export-" + now + "page-" + i + ".pdf";
file = new File(filePath);
document.exportFile(ExportFormat.pdfType, file, false, app.pdfExportPresets.item(PDF_EXPORT_PRESET.name));
progressStatus.text = "Uploading side " + (i + 1) + " to MOO";
progressPanel.update();
var imageBasketItem = uploadToMOO(file, function(update) {
progressStatus.text = "Uploading side " + (i + 1) + " to MOO: " + update;
progressPanel.update();
});
if (!imageBasketItem) {
progressPanel.hide();
alert('Sorry -- the upload to MOO failed. Try again later :(');
return;
}
imageBasketItems.push(imageBasketItem);
} finally {
if (file) {
file.remove();
}
}
}
progressStatus.text = "Creating pack";
progressPanel.update();
var packData = simplePack(document, imageBasketItems, size);
var url = createPack(size.mooName, packData, function(update) {
progressStatus.text = "Sending pack to MOO: " + update;
progressPanel.update();
});
if (!url) {
progressPanel.hide();
alert('Sorry -- there was a problem with creating your pack. Try again later :(');
return;
}
visit(url);
// var completedDialog = new Window('dialog', 'Pack Ready');
// var completedMessage = completedDialog.add('statictext');
// completedMessage.text = "Your pack is available at " + url;
// completedDialog.add('button', undefined, 'Yay!', {name: 'OK'});
// completedDialog.show();
} finally {
progressPanel.hide();
}
};
var addImageSide = app.scriptMenuActions.add("Add image side");
addImageSide.addEventListener('onInvoke', addPageAction('image'));
mooMenu.menuItems.add(addImageSide);
var addDetailsSide = app.scriptMenuActions.add("Add details side");
addDetailsSide.addEventListener('onInvoke', addPageAction('details'));
mooMenu.menuItems.add(addDetailsSide);
var changeToImageSide = app.scriptMenuActions.add("Change to image side");
changeToImageSide.addEventListener('onInvoke', changePageAction('image'));
mooMenu.menuItems.add(changeToImageSide);
var changeToDetailsSide = app.scriptMenuActions.add("Change to details side");
changeToDetailsSide.addEventListener('onInvoke', changePageAction('details'));
mooMenu.menuItems.add(changeToDetailsSide);
var sendToMoo = app.scriptMenuActions.add("Send to MOO...");
sendToMoo.addEventListener('onInvoke', uploadAction);
mooMenu.menuItems.add(sendToMoo);
var uploadCheck = function uploadCheck() {
var document = null;
try {
var document = app.activeDocument;
} catch (myError) {
}
if (document && sizeForDocument(document)) {
addImageSide.enabled = true;
addDetailsSide.enabled = true;
sendToMoo.enabled = true;
} else {
addImageSide.enabled = false;
addDetailsSide.enabled = false;
sendToMoo.enabled = false;
}
}
var switchCheck = function switchCheck() {
var document = null;
try {
var document = app.activeDocument;
} catch (myError) {
}
if (document && sizeForDocument(document)) {
var page = null;
try {
var page = app.activeWindow.activePage;
} catch (myError) {
}
if (page) {
changeToImageSide.enabled = sideTypeForPage(page) !== 'image';
changeToDetailsSide.enabled = sideTypeForPage(page) !== 'details';
}
} else {
changeToImageSide.enabled = false;
changeToDetailsSide.enabled = false;
}
}
addImageSide.addEventListener('beforeDisplay', uploadCheck);
addDetailsSide.addEventListener('beforeDisplay', uploadCheck);
sendToMoo.addEventListener('beforeDisplay', uploadCheck);
changeToImageSide.addEventListener('beforeDisplay', switchCheck);
changeToDetailsSide.addEventListener('beforeDisplay', switchCheck);
})();
//-----------------------------------------------------------------------------
/*
* Copyright 2008 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Here's some JavaScript software for implementing OAuth.
This isn't as useful as you might hope. OAuth is based around
allowing tools and websites to talk to each other. However,
JavaScript running in web browsers is hampered by security
restrictions that prevent code running on one website from
accessing data stored or served on another.
Before you start hacking, make sure you understand the limitations
posed by cross-domain XMLHttpRequest.
On the bright side, some platforms use JavaScript as their
language, but enable the programmer to access other web sites.
Examples include Google Gadgets, and Microsoft Vista Sidebar.
For those platforms, this library should come in handy.
*/
// The HMAC-SHA1 signature method calls b64_hmac_sha1, defined by
// http://pajhome.org.uk/crypt/md5/sha1.js
/* An OAuth message is represented as an object like this:
{method: "GET", action: "http://server.com/path", parameters: ...}
The parameters may be either a map {name: value, name2: value2}
or an Array of name-value pairs [[name, value], [name2, value2]].
The latter representation is more powerful: it supports parameters
in a specific sequence, or several parameters with the same name;
for example [["a", 1], ["b", 2], ["a", 3]].
Parameter names and values are NOT percent-encoded in an object.
They must be encoded before transmission and decoded after reception.
For example, this message object:
{method: "GET", action: "http://server/path", parameters: {p: "x y"}}
... can be transmitted as an HTTP request that begins:
GET /path?p=x%20y HTTP/1.0
(This isn't a valid OAuth request, since it lacks a signature etc.)
Note that the object "x y" is transmitted as x%20y. To encode
parameters, you can call OAuth.addToURL, OAuth.formEncode or
OAuth.getAuthorization.
This message object model harmonizes with the browser object model for
input elements of an form, whose value property isn't percent encoded.
The browser encodes each value before transmitting it. For example,
see consumer.setInputs in example/consumer.js.
*/
/* This script needs to know what time it is. By default, it uses the local
clock (new Date), which is apt to be inaccurate in browsers. To do
better, you can load this script from a URL whose query string contains
an oauth_timestamp parameter, whose value is a current Unix timestamp.
For example, when generating the enclosing document using PHP:
<script src="oauth.js?oauth_timestamp=<?=time()?>" ...
Another option is to call OAuth.correctTimestamp with a Unix timestamp.
*/
var OAuth; if (OAuth == null) OAuth = {};
OAuth.setProperties = function setProperties(into, from) {
if (into != null && from != null) {
for (var key in from) {
into[key] = from[key];
}
}
return into;
}
OAuth.setProperties(OAuth, // utility functions
{
percentEncode: function percentEncode(s) {
if (s == null) {
return "";
}
if (s instanceof Array) {
var e = "";
for (var i = 0; i < s.length; ++s) {
if (e != "") e += '&';
e += OAuth.percentEncode(s[i]);
}
return e;
}
// http://bytes.com/topic/javascript/answers/739466-url-encoding-string-code-worth-recommending-project
s = encodeURIComponent(s).replace(/(.{0,3})(%0A)/g, function(m, p1, p2) {
return p1 + (p1 == '%0D' ? '' : '%0D') + p2;
});
// Now replace the values which encodeURIComponent doesn't do
// encodeURIComponent ignores: - _ . ! ~ * ' ( )
// OAuth dictates the only ones you can ignore are: - _ . ~
// Source: http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Functions:encodeURIComponent
s = s.replace(/\!/g, "%21");
s = s.replace(/\*/g, "%2A");
s = s.replace(/\'/g, "%27");
s = s.replace(/\(/g, "%28");
s = s.replace(/\)/g, "%29");
return s;
}
,
decodePercent: function decodePercent(s) {
if (s != null) {
// Handle application/x-www-form-urlencoded, which is defined by
// http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
s = s.replace(/\+/g, " ");
}
return decodeURIComponent(s);
}
,
/** Convert the given parameters to an Array of name-value pairs. */
getParameterList: function getParameterList(parameters) {
if (parameters == null) {
return [];
}
if (typeof parameters != "object") {
return OAuth.decodeForm(parameters + "");
}
if (parameters instanceof Array) {
return parameters;
}
var list = [];
for (var p in parameters) {
list.push([p, parameters[p]]);
}
return list;
}
,
/** Convert the given parameters to a map from name to value. */
getParameterMap: function getParameterMap(parameters) {
if (parameters == null) {
return {};
}
if (typeof parameters != "object") {
return OAuth.getParameterMap(OAuth.decodeForm(parameters + ""));
}
if (parameters instanceof Array) {
var map = {};
for (var p = 0; p < parameters.length; ++p) {
var key = parameters[p][0];
if (map[key] === undefined) { // first value wins
map[key] = parameters[p][1];
}
}
return map;
}
return parameters;
}
,
getParameter: function getParameter(parameters, name) {
if (parameters instanceof Array) {
for (var p = 0; p < parameters.length; ++p) {
if (parameters[p][0] == name) {
return parameters[p][1]; // first value wins
}
}
} else {
return OAuth.getParameterMap(parameters)[name];
}
return null;
}
,
formEncode: function formEncode(parameters) {
var form = "";
var list = OAuth.getParameterList(parameters);
for (var p = 0; p < list.length; ++p) {
var value = list[p][1];
if (value == null) value = "";
if (form != "") form += '&';
form += OAuth.percentEncode(list[p][0])
+'='+ OAuth.percentEncode(value);
}
return form;
}
,
decodeForm: function decodeForm(form) {
var list = [];
var nvps = form.split('&');
for (var n = 0; n < nvps.length; ++n) {
var nvp = nvps[n];
if (nvp == "") {
continue;
}
var equals = nvp.indexOf('=');
var name;
var value;
if (equals < 0) {
name = OAuth.decodePercent(nvp);
value = null;
} else {
name = OAuth.decodePercent(nvp.substring(0, equals));
value = OAuth.decodePercent(nvp.substring(equals + 1));
}
list.push([name, value]);
}
return list;
}
,
setParameter: function setParameter(message, name, value) {
var parameters = message.parameters;
if (parameters instanceof Array) {
for (var p = 0; p < parameters.length; ++p) {
if (parameters[p][0] == name) {
if (value === undefined) {
parameters.splice(p, 1);
} else {
parameters[p][1] = value;
value = undefined;
}
}
}
if (value !== undefined) {
parameters.push([name, value]);
}
} else {
parameters = OAuth.getParameterMap(parameters);
parameters[name] = value;
message.parameters = parameters;
}
}
,
setParameters: function setParameters(message, parameters) {
var list = OAuth.getParameterList(parameters);
for (var i = 0; i < list.length; ++i) {
OAuth.setParameter(message, list[i][0], list[i][1]);