From ae0c6b3e1b21b3b06ebbbe5c5fd31f1ae2ed5217 Mon Sep 17 00:00:00 2001 From: zmv7 <72821250+zmv7@users.noreply.github.com> Date: Mon, 2 Nov 2020 09:08:31 +0500 Subject: [PATCH] Add files via upload --- mag/debug.html | 160 ++ mag/events.txt | 31 + mag/history.md | 708 ++++++ mag/index.html | 14 + mag/rules.js | 32 + mag/services.html | 795 ++++++ mag/test.html | 49 + mag/tests/index.html | 26 + mag/tests/jsondb.js | 18 + mag/tests/jsondbtable.js | 208 ++ mag/tests/qunit/qunit-1.13.0.css | 245 ++ mag/tests/qunit/qunit-1.13.0.js | 2210 +++++++++++++++++ mag/tests/storage.js | 37 + mag/tests/winapi.js | 30 + mag/tools/build.gettext.cmd | 74 + mag/tools/build.gettext.sh | 73 + mag/tools/build.help.cmd | 5 + mag/tools/build.help.sh | 3 + mag/tools/build.release.cmd | 5 + mag/tools/build.release.sh | 3 + mag/tools/gethelp.js | 48 + mag/tools/gettext.js | 101 + mag/tools/help-generator/HelpGenerator.php | 220 ++ mag/tools/help-generator/aceeditor/action.php | 96 + mag/tools/help-generator/readme.txt | 13 + mag/tools/http.server.cmd | 1 + mag/tools/http.server.js | 14 + mag/tools/models.js | 69 + mag/tools/package.json | 28 + mag/tools/readme.md | 14 + mag/tools/release.js | 153 ++ mag/tools/stb-proxy/client.js | 110 + mag/tools/stb-proxy/server.js | 84 + mag/tools/stb-proxy/start.html | 44 + mag/tools/stb-proxy/start.js | 96 + mag/tools/stb-proxy/tests/client.a.html | 20 + mag/tools/stb-proxy/tests/client.b.html | 20 + mag/tools/stb-proxy/tests/server.a.html | 20 + mag/tools/stb-proxy/tests/server.b.html | 20 + mag/tools/stb-proxy/wspool.js | 109 + 40 files changed, 6006 insertions(+) create mode 100644 mag/debug.html create mode 100644 mag/events.txt create mode 100644 mag/history.md create mode 100644 mag/index.html create mode 100644 mag/rules.js create mode 100644 mag/services.html create mode 100644 mag/test.html create mode 100644 mag/tests/index.html create mode 100644 mag/tests/jsondb.js create mode 100644 mag/tests/jsondbtable.js create mode 100644 mag/tests/qunit/qunit-1.13.0.css create mode 100644 mag/tests/qunit/qunit-1.13.0.js create mode 100644 mag/tests/storage.js create mode 100644 mag/tests/winapi.js create mode 100644 mag/tools/build.gettext.cmd create mode 100644 mag/tools/build.gettext.sh create mode 100644 mag/tools/build.help.cmd create mode 100644 mag/tools/build.help.sh create mode 100644 mag/tools/build.release.cmd create mode 100644 mag/tools/build.release.sh create mode 100644 mag/tools/gethelp.js create mode 100644 mag/tools/gettext.js create mode 100644 mag/tools/help-generator/HelpGenerator.php create mode 100644 mag/tools/help-generator/aceeditor/action.php create mode 100644 mag/tools/help-generator/readme.txt create mode 100644 mag/tools/http.server.cmd create mode 100644 mag/tools/http.server.js create mode 100644 mag/tools/models.js create mode 100644 mag/tools/package.json create mode 100644 mag/tools/readme.md create mode 100644 mag/tools/release.js create mode 100644 mag/tools/stb-proxy/client.js create mode 100644 mag/tools/stb-proxy/server.js create mode 100644 mag/tools/stb-proxy/start.html create mode 100644 mag/tools/stb-proxy/start.js create mode 100644 mag/tools/stb-proxy/tests/client.a.html create mode 100644 mag/tools/stb-proxy/tests/client.b.html create mode 100644 mag/tools/stb-proxy/tests/server.a.html create mode 100644 mag/tools/stb-proxy/tests/server.b.html create mode 100644 mag/tools/stb-proxy/wspool.js diff --git a/mag/debug.html b/mag/debug.html new file mode 100644 index 0000000..4c7a5d6 --- /dev/null +++ b/mag/debug.html @@ -0,0 +1,160 @@ + + + + Debug entry point + + + + + + + + + + + + + + + + + +
+ + + + + + + + +
Proxy server address:Session name:
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Service page
System settings
Portal loader
Download manager
Record manager
Internet browser
Internet bookmarks
Help
+
+ + \ No newline at end of file diff --git a/mag/events.txt b/mag/events.txt new file mode 100644 index 0000000..cff52fd --- /dev/null +++ b/mag/events.txt @@ -0,0 +1,31 @@ +//All global events + +//Reload given window +"window.reload" + +//Load given URL (has 1 param {String} - new window URL) +"window.load" + +// Player end playing some file +"player.end" + +// Play file. (has 1 param {String} - file url) +"player.play" + +// usb device has been mounted +"broadcast.storage.mount" + +// accessControl state has been change +"broadcast.accessControl" + +// usb device has been unmounted +"broadcast.storage.unmount" + +// sent (wake up) device to (from) standby mode +"portal.standbyMode" + +// reload environment variables +"environment.reload" + +// reset player resolution data according to new video mode +"video.mode.reload" diff --git a/mag/history.md b/mag/history.md new file mode 100644 index 0000000..e530713 --- /dev/null +++ b/mag/history.md @@ -0,0 +1,708 @@ +History +======= + +## 2020.08.14 ## + +* enable bluetooth support only for specific devices +* force disable bluetooth and clear env for unsupported devices + + +## 2020.07.21 ## + +* delete Magic Cast application + + +## 2020.07.03 ## + +* fix update resolution on HDMI connect event +* fix review warnings + + +## 2020.06.25 ## + +* add IM4411WV model support +* add IM4410WV model support + + +## 2020.06.04 ## + +* remove overlapping of bookmarks modal by autocomplete +* fix logic of changing F3 footer button +* initialize Widevine for IPTV playlists if allowed +* fix handle focus on items in Explorer +* remove selection from added items inside Favorites +* add support for whole cyrillic letters range in URL validation + + +## 2020.05.07 ## + +* add implementation for external page loading delay +* select view as uniq to prevent loosing text +* add check condition for setting delay +* encode input fragment only for search mode + + +## 2020.04.23 ## + +* switch by default to the highest qulity for HLS + + +## 2020.04.21 ## + +* fix obtain "addresses" property for mount config + + +## 2020.04.14 ## + +* add SRT as stream protocol in URL validator, refactor + + +## 2020.04.10 ## + +* add basic support for Widevine DRM playlists +* fix manual mounting of SMB share + + +## 2020.03.26 ## + +* encode URL spaces and pluses (+) in appropriate way +* remove unescaping of explicit URL encoding symbols + + +## 2020.03.11 ## + +* fix reaction when error occured during slideshow + + +## 2020.03.04 ## + +* switch to HTTPS for update lists + + +## 2020.01.23 ## + +* add IM4411V model support +* fix demo page loading by preventing parse wrong font files + + +## 2019.10.31 ## + +* fix help generator +* add sorting by number in m3u parser + + +## 2019.10.18 ## + +* add device reload after user data cleared +* fix server part of help-generator for php 7 version +* fix background after removing all channels + + +## 2019.10.11 ## + +* fix timeshift start error modal + + +## 2019.10.09 ## + +* skip privacy policy not only in loader but in portal too + + +## 2019.09.26 ## + +* fix hiding modal behavior to prevent from show webinput results +* prevent of showing webinput result box on exit from menu by Exit button +* fix mounting share by domain name, remove IP validation +* improve code quality + + +## 2019.09.03 ## + +* fix review warnings +* fix checkbox styles for 576 and 480 resolution + + +## 2019.08.19 ## + +* fix teletext in 4k resolution + + +## 2019.08.14 ## + +* fix initial mute state after reload portal +* add 4k resolution for MAG422 + + +## 2019.08.06 ## + +* portals loader: add privacy policy reset +* fix focus item in IPTV Channels after empty list + + +## 2019.07.25 ## + +* fix update list url for IM2101VO + + +## 2019.07.05 ## + +* fix init volume setting change + + +## 2019.07.04 ## + +* portals loader: remove HEAD request from portal availability check and use only GET request (some clients have strangely configured servers) + + +## 2019.07.01 ## + +* player: fix jscs +* player: don't show error message for same file twice +* player: exit from player after error message for bad images in non-slideshow mode +* player: show error message for bad images + + +## 2019.06.12 ## + +* loader: fix embedded portal loading in multiportal mode +* loader: fix jscs + + +## 2019.06.10 ## + +* loader: fix jscs +* loader: remove exit button from privacy policy +* loader: add checks for different ajax errors, fix abort function in ajax +* loader: fix interface + + +## 2019.06.05 ## + +* loader: add new exit button +* fix teletext option setup for low resolutions instead of low video modes +* help: add privacy policy agreement +* help generator: update to php 7 +* fix player teletext settings saving +* fix navigation in player teletext settings + + +## 2019.05.30 ## + +* remove tif format support from mag322 +* loader: fix long names problems + + +## 2019.05.17 ## + +* fix loader + + +## 2019.05.08 ## + +* remove tif format for mag322 +* loader page rework and optimizations + + +## 2019.04.25 ## + +* fix list vertical align in DVB channels + + +## 2019.04.18 ## + +* add IM2101VO model support +* remove .raw format support for mag322 + + +## 2019.04.11 ## + +* add IM4411 model support + + +## 2019.03.27 ## + +* add IM4412 model support +* add IM2101VI model support + + +## 2019.03.25 ## + +* remove some user data from speedtest and traceroute reports for aura + + +## 2019.02.13 ## + +* fix advanced settings in access control +* add 4k resolution for MAG420 +* fix wifi manual settings +* fix set subtitles black color +* fix load manual wifi settings + + +## 2019.02.07 ## + +* fix weather in master settings + + +## 2019.01.28 ## + +* fix text in popup which appears for blocked portals + + +## 2019.01.22 ## + +* fix name overlap in update modal +* add 'utf-16be' and 'utf-16le' subtitles encoding +* fix fast load in loader +* fix access control in loader + + +## 2019.01.02 ## + +* fix update start + + +## 2018.12.27 ## + +* update exit_wraper_bg.png from 2x2 to 100x100 size +* fix event handler in update modal + + +## 2018.12.10 ## + +* support difference between mag254 and mag322 wifi event status implementation +* add mag420 model support + + +## 2018.12.05 ## + +* correct updateList for MAG422 + + +## 2018.11.30 ## + +* fix UPnPRendererClear error +* change keydown listener to keypress in tattelecom code +* update dvb scanning modals + + +## 2018.11.15 ## + +* fix focused out of array +* fix code style + + +## 2018.11.07 ## + +* add mag422, remove PPPoE for mag422, mag424, mag425 from system settings + + +## 2018.10.30 ## + +* fix error handler for playlist update request +* remove forcing enabling service button +* hide unsupported settings for IM2100V, IM2100VI (resolution and network settings) + + +## 2018.09.18 ## + +* add contact data to warning text at "url is blocked" page +* add IM2100VI model support + + +## 2018.09.07 ## + +* add check for async work of bluetooth API function at mag424 (stbBluetooth.enable) +* fix channels list loading +* fix start play object without url in player + + +## 2018.08.23 ## + +* fix event propagation + + +## 2018.08.21 ## + +* update manual +* update localization +* fix empty audio_initial_volume state + + +## 2018.08.13 ## + +* fix change position + + +## 2018.08.07 ## + +* fix localization + + +## 2018.07.30 ## + +* fix saving zero volume +* fix localization + + +## 2018.07.19 ## + +* disable stbUPnPRenderer and clear code + + +## 2018.07.11 ## + +* fix current image date check in update + + +## 2018.06.01 ## + +* increase portal loading delay in multiportal mode to fix slow wifi start + + +## 2018.05.24 ## + +* add IM2100V model support +* remove games from portal +* remove games section from manual + + +## 2018.05.17 ## + +* fix update check: remove influence of device local time zone + + +## 2018.05.07 ## + +* fix incorrectly encoded urls in API event + + +## 2018.04.27 ## + +* add IM2101 device support +* fix navigation in favorite, fix style in DVB Channels + + +## 2018.04.24 ## + +* remove DVB settings for IM2102 +* fix navigation in DVB channels +* fix DVB channels item style + + +## 2018.04.13 ## + +* fix access control settings + + +## 2018.04.12 ## + +* add modal window with info on url blocking + + +## 2018.04.10 ## + +* add IM2102 device support + + +## 2018.04.03 ## + +* add IM2100 device support +* change title LED brightness (standby) in settings +* add stbUPnP.deinit in system settings + + +## 2018.03.26 ## + +* add MAG424 device support +* fix checkbox style in settings +* correct configs for MAG424/425/351/352 + + +## 2018.02.19 ## + +* add new timezone codes +* always check environment variables portal1 and portal2 for possible operator changes (and apply them) +* change statistic server url +* optimise auto update requests +* disable 1920x1080 graphic resolution for AuraHD4 + + +## 2018.02.16 ## + +* fix translation +* fix opening Home Media resources after UPnP failure +* fix retrieving search data from Google for autocomplete +* improve saving algorithm in timeshift +* don't show auto power down if timeshift is active +* renew environment variables values after correction by operator + + +## 2018.01.24 ## + +* remove 1080p resolution selection in settings for mag322 + + +## 2018.01.19 ## + +* request timeout for retrieving the help archive has been increased +* fix video settings +* fix wifi keys generation page + + +## 2018.01.09 ## + +* fix mounting share by hand +* remove DVB setting for AuraHD4 + + +## 2017.12.26 ## + +* fix wrong url for auto update on MAG276 +* remove misspelling from auto update url in auraHD4 +* comment cleanup trash download tasks for unmounted storages (cleanup triggers by unmount event) +* cleanup trash download tasks for unmounted storages (cleanup triggers by unmount event) + + +## 2017.12.18 ## + +* fix value parsing for auto update condition variable + + +## 2017.11.29 ## + +* add missing codec image to cache list +* fix item focusing in media browser on player event +* fix missing environment variables for sending headers on update +* optimize player and explorer pages switching + +## 2017.11.27 ## + +* add new headers (X-Portal1 and X-Portal2) in update list request +* fix save resolution in settings +* don't send update check request after update modal window exit + + +## 2017.11.20 ## + +* add new headers in update list request +* disable password field for NFS mounting +* change logo for AuraHD 4 + + +## 2017.11.17 ## + +* add AC3+ audio type +* fix interface error in download app on quick multiple tasks creation +* add speed test for mag35* + + +## 2017.11.07 ## + +* remove PPPoE for AuraHD* +* update updateList url for MAG256 and MAG351 + + +## 2017.10.30 ## + +* fix reload portal after change settings + + +## 2017.10.13 ## + +* add untune dvb input in DVB channels +* fix focus item in Media Browser +* correct supported files types list for mag322 + + +## 2017.09.28 ## + +* add AuraHD4 device config and logo +* fix pause icon in download manager +* fix reload portal after change settings +* fix teletext settings +* add logo for mag425 + + +## 2017.09.14 ## + +* fix reboot device after reset settings +* fix problem with chapters list in player for DVD content +* fix reload portal message after reset settings +* add mag324c and mag325c logo images + + +## 2017.09.04 ## + +* add mag324c and mag325c logo images + + +## 2017.08.28 ## + +* fix wifi, internet and network states +* update localizations +* add .wtv extension to supported files + + +## 2017.08.17 ## + +* fix mag349 config +* change format wifi_off from boolean to number +* update registers types in config for mag3** series +* fix wifi state change + + +## 2017.08.11 ## + +* add wifi disable button and state change hook +* fix enable wifi button state + + +## 2017.08.09 ## + +* fix ts time save +* add to settings information about rootFS version +* fix update url for mag324c +* remove 'No ip' settings for MAG322, MAG324C + + +## 2017.07.28 ## + +* fix editing iptv channels, remove unc option from SMB mount + + +## 2017.07.26 ## + +* remove PPPoE from network settings on MAG324C + + +## 2017.07.25 ## + +* fix adding channels to IPTV playlist +* checking API version for set appropriate method signatures on open samba host +* fix unc address syntax on cifs mount + + +## 2017.07.24 ## + +* add hash info to build metadata +* add MAG324C model support +* protect parsing AJAX request for update list result +* remove PPPoE from settings for MAG322 + + +## 2017.07.14 ## + +* add auth for SMB servers and rework error handling +* fix tv url parsing +* hide password and fix mounting share by hand +* fix manual mounting in SAMBA browser +* store auth data of successful connections to SMB servers +* open SAMBA server even if it's password protected + + +## 2017.06.23 ## + +* hide info panel on bluetooth disable +* realize opening shares with multiple IPs + + +## 2017.06.14 ## + +* add mac to auto update list request as query param + + +## 2017.05.22 ## + +* add warning message in case of NAND bank damage +* show actual NAND number in settings (with emergency status info) + + +## 2017.05.15 ## + +* add MAGic Cast menu item +* fix bluetooth adapter disabling when some device is connected +* fix .m3u parser +* fix audio playing info panel state in player + + +## 2017.04.26 ## + +* add "wtv" video file format support + + +## 2017.04.25 ## + +* fix playback on video mode change +* fix empty Bluetooth device list handlers + + +## 2017.04.14 ## + +* set dynamic range compression for DolbyDigital audio on player initialization +* remove "Dynamic range compression" option from settings +* restrict "Operating mode" audio setting to "RF Mode" and "Line Mode" only + + +## 2017.04.12 ## + +* update codec icons in player + + +## 2017.04.05 ## + +* correct manual localization + + +## 2017.03.31 ## + +* fix selected chapter after change position in DVD or ISO files +* fix #6534, read cue and m3u playlists equally +* remove dead code (variable STB_MODE_STANDBY) and fix multiple net status function call +* add flag IPTV_PLAYBACK_ON_START to start first channel in full screen + + +## 2017.03.29 ## + +fix usb unmount when something is playing + + +## 2017.03.28 ## + +* save bluetooth enabled state in environment +* remove unused device characteristics + + +## 2017.03.27 ## + +* fix player preview position +* bluetooth: sort devices by paired and active +* fix bug with partially transparent overlay +* fix localization + + +## 2017.03.16 ## + +* add device config to json generator +* add devices logos +* add bluetooth translations +* rework bluetooth api +* add MAG323 model support +* fix image preview +* fix subtitles and teletext subtitles +* add rotate image in player menu +* fix localisation + + +## 2017.03.01 ## + +* Add MAG324/MAG325 device support +* Add img format #11116 +* Solve #11048 + + +## 2017.02.22 ## + +* hide gSTB error message until we get localisation for it +* title field shouldn't rewrite lang field and if title field available use it instead of localised type text +* upgrade error page ping diff --git a/mag/index.html b/mag/index.html new file mode 100644 index 0000000..f39302f --- /dev/null +++ b/mag/index.html @@ -0,0 +1,14 @@ + + + + + new MAG 200-250 + + + + + + + \ No newline at end of file diff --git a/mag/rules.js b/mag/rules.js new file mode 100644 index 0000000..8331f39 --- /dev/null +++ b/mag/rules.js @@ -0,0 +1,32 @@ +'use strict'; + +/** + * Customization rules for manual tune + * @author Stanislav Kalashnik + * @namespace + */ +var RULES = { + + 'Playback' : true, + + 'Interface' : true, + + 'SoftwareAutoUpdate': true, + + 'TimeShift' : true, + + 'SpeedTest' : true, + + 'Traceroute' : true, + + 'SystemSettings' : true, + + 'SetupWizard' : true, + + 'DVB' : true, + + 'accessControl' : true, + + 'teletext' : true + +}; diff --git a/mag/services.html b/mag/services.html new file mode 100644 index 0000000..d05d387 --- /dev/null +++ b/mag/services.html @@ -0,0 +1,795 @@ + + + + STB Service page + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ Loading... +
+ + + + + + + + + + +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + + +
+ + + + + + + + + + + + + + + + + +
+ + + + + + + +
+
+ +
+
+
+ + + +
+ +
+ + + + + + + + + + + + + + + + + + +
+ + + + + + + +
+
+ + + + + +
+ +
+
+
+
+
+ +
+
+ +
+
+
+ +
+ + + +
+ +
+ + + + + + + + + + + + + + + + + + + +
+ + + + + + + +
+
+ + + + + +
+ +
+
+
+
+
+
+
+
+
+ +
+ + +
+ + + + + + + + + + + + + + + + + +
+ + + + + +
+
+ + + + + + + + + + + +
+ + +
+
+
+
+
+ +
+ + + +
+ +
+ + + + + + + + + + + + + + + + + + + +
+ + + + + + + +
+
+ + + + + +
+ +
+
+
+ + + + + + + + +
+ +
+
+ Records: 0 +
+
+ Selected: 0 +
+
+
+
+
+ + + +
+ + + + + + +
+ + +
+
+ +
+
+ + +
+
+ + + +
+ + +
00:00
+ + + + + +
+ + +
+ + + +
+ + + + + +
+ + + + + + + diff --git a/mag/test.html b/mag/test.html new file mode 100644 index 0000000..f3d2724 --- /dev/null +++ b/mag/test.html @@ -0,0 +1,49 @@ + + + + + Title + + + + + +
+ + + diff --git a/mag/tests/index.html b/mag/tests/index.html new file mode 100644 index 0000000..7849426 --- /dev/null +++ b/mag/tests/index.html @@ -0,0 +1,26 @@ + + + + + Module testing + + + +
+
+ + + + + + + + + + + + diff --git a/mag/tests/jsondb.js b/mag/tests/jsondb.js new file mode 100644 index 0000000..4b416c9 --- /dev/null +++ b/mag/tests/jsondb.js @@ -0,0 +1,18 @@ +'use strict'; + +module('jsonDb'); + +test('constructor', function () { + var db = new jsonDb(); + strictEqual(db.constructor.name, 'jsonDb', 'constructor name'); + strictEqual(typeof db.data, 'object', 'db data type'); +}); + +test('table', function () { + var db = new jsonDb(); + strictEqual(db.table(), false, 'table lookup by empty name'); + + var test = db.table('test'); + strictEqual(test.constructor.name, 'jsonDbTable', 'constructor name'); + strictEqual(typeof test.data, 'object', 'table data type'); +}); \ No newline at end of file diff --git a/mag/tests/jsondbtable.js b/mag/tests/jsondbtable.js new file mode 100644 index 0000000..6a90a62 --- /dev/null +++ b/mag/tests/jsondbtable.js @@ -0,0 +1,208 @@ +'use strict'; + +module('jsonDbTable'); + +test('constructor', function () { + var test = new jsonDbTable(); + strictEqual(test.constructor.name, 'jsonDbTable', 'constructor name'); + strictEqual(typeof test.data, 'object', 'table data type'); +}); + +test('init', function () { + var db = new jsonDb(); + var test = db.table('test'); + strictEqual(test.init(), false, 'table init with no data'); + + strictEqual(test.init('id'), true, 'table init with 3 columns'); + deepEqual(test.data, {rows: {}, idName: 'id', rowIdx: 0, fldIds: [], fldIdx: {}}, 'table internal data structure'); + + strictEqual(test.init('_id', 'name', 'data'), true, 'table init with 3 columns'); + deepEqual(test.data, {rows: {}, idName: '_id', rowIdx: 0, fldIds: ['name', 'data'], fldIdx: {name: 0, data: 1}}, 'table internal data structure'); + strictEqual(test.add(1), true, 'add partial row'); + + strictEqual(test.init('id', 'name'), true, 'table reinit with 2 columns'); + deepEqual(test.data, {rows: {}, idName: 'id', rowIdx: 0, fldIds: ['name'], fldIdx: {name: 0}}, 'table internal data structure'); +}); + +test('genId', function () { + var db = new jsonDb(); + var test = db.table('test'); + test.init('id', 'name', 'type'); + strictEqual(test.genId(), '1', 'counter increment'); + strictEqual(test.genId(), '2', 'counter increment'); + strictEqual(test.genId(), '3', 'counter increment'); + strictEqual(test.data.rowIdx, 3, 'counter increment'); +}); + +test('add', function () { + var db = new jsonDb(); + var test = db.table('test'); + strictEqual(test.init('id', 'name', 'type'), true, 'table init with 3 columns'); + + strictEqual(test.add(), false, 'add empty row'); + strictEqual(test.add(null), false, 'add empty row'); + strictEqual(test.add(null, 5, 8), false, 'add empty row'); + strictEqual(test.add(undefined), false, 'add empty row'); + strictEqual(test.add(null, null, null), false, 'add empty row'); + + strictEqual(test.add(1), true, 'add partial row'); + strictEqual(Object.keys(test.data.rows).length, 1, 'table rows count'); + deepEqual(test.data.rows[1], [null, null], 'row data check'); + + strictEqual(test.add('2', 'name1', 'type1'), true, 'add full row'); + deepEqual(test.data.rows[2], ['name1', 'type1'], 'row data check'); + strictEqual(Object.keys(test.data.rows).length, 2, 'table rows count'); + + strictEqual(test.add(3, {a: 1, b: 2}, [2, 4, 8]), true, 'add full complex row'); + deepEqual(test.data.rows[3], [ + {a: 1, b: 2}, + [2, 4, 8] + ], 'row data check'); + + strictEqual(test.add(4, false, undefined), true, 'add partly empty row'); + deepEqual(test.data.rows[4], [false, null], 'row data check'); + + strictEqual(test.add('5', 0, true), true, 'add partly empty row'); + deepEqual(test.data.rows[5], [0, true], 'row data check'); + + strictEqual(test.add(6, {}, []), true, 'add partly empty row'); + deepEqual(test.data.rows[6], [ + {}, + [] + ], 'row data check'); + + strictEqual(test.add(7, 1, 2, 3, 4, 5), true, 'add row with too many columns'); + deepEqual(test.data.rows[7], [1, 2], 'row data check'); + + strictEqual(test.add('8', 'a'), true, 'add partial row'); + deepEqual(test.data.rows[8], ['a', null], 'row data check'); + + strictEqual(test.add(8), false, 'add duplicate id row'); + strictEqual(test.add(8, 'a'), false, 'add duplicate id row'); + strictEqual(test.add(8, 'b', 'c'), false, 'add duplicate id row'); +}); + +test('get', function () { + var db = new jsonDb(); + var test = db.table('test'); + test.init('id', 'name', 'type'); + test.add(1); + test.add(2, 'name1', 'type1'); + test.add(3, {a: 1, b: 2}, [2, 4, 8]); + test.add(4, false, undefined); + test.add(5, 0, true); + test.add(6, {}, []); + test.add(7, 1, 2, 3, 4, 5); + test.add(8, 'a'); + strictEqual(Object.keys(test.data.rows).length, 8, 'table rows count'); + + deepEqual(test.get(1), {id: '1', name: null, type: null}, 'row data check'); + deepEqual(test.get(2), {id: '2', name: 'name1', type: 'type1'}, 'row data check'); + deepEqual(test.get(3), {id: '3', name: {a: 1, b: 2}, type: [2, 4, 8]}, 'row data check'); + deepEqual(test.get(4), {id: '4', name: false, type: null}, 'row data check'); + deepEqual(test.get('7'), {id: '7', name: 1, type: 2}, 'row data check'); + deepEqual(test.get(123), false, 'row data check'); + deepEqual(test.get(null), false, 'row data check'); + deepEqual(test.get(undefined), false, 'row data check'); + deepEqual(test.get(5, 'name'), 0, 'row field data check'); + deepEqual(test.get(2, 'type'), 'type1', 'row field data check'); +}); + +test('set', function () { + var db = new jsonDb(); + var test = db.table('test'); + test.init('id', 'name', 'type'); + + strictEqual(test.set(), false, 'empty wrong data'); + strictEqual(test.set(null), false, 'empty wrong data'); + strictEqual(test.set(''), false, 'empty wrong data'); + strictEqual(test.set(0), false, 'empty wrong data'); + strictEqual(test.set(null, null), false, 'empty wrong data'); + strictEqual(test.set(1, null), false, 'empty wrong data'); + strictEqual(test.set(1, 2), false, 'wrong data'); + strictEqual(test.set(1, ''), false, 'wrong data'); + strictEqual(test.set(1, 'sdfg'), false, 'wrong data'); + strictEqual(Object.keys(test.data.rows).length, 0, 'table rows count'); + + strictEqual(test.set(1, []), true, 'empty data'); + deepEqual(test.data.rows[1], [null, null], 'row data check'); + strictEqual(test.set(1, {}), true, 'empty data'); + deepEqual(test.data.rows[1], [null, null], 'row data check'); + + strictEqual(test.set(1, {name: 'qwe'}), true, 'update data'); + deepEqual(test.data.rows[1], ['qwe', null], 'row data check'); + + strictEqual(test.set(1, {name: 'qwe2'}), true, 'update data'); + deepEqual(test.data.rows[1], ['qwe2', null], 'row data check'); + + strictEqual(test.set(1, {type: 'rty'}), true, 'update data'); + deepEqual(test.data.rows[1], ['qwe2', 'rty'], 'row data check'); + + strictEqual(test.set(1, {data: 'some'}), true, 'update non-existing field'); + deepEqual(test.data.rows[1], ['qwe2', 'rty'], 'row data check'); + + strictEqual(test.set(1, {name: 'qwe3', data: 'some'}), true, 'update existing and non-existing fields'); + deepEqual(test.data.rows[1], ['qwe3', 'rty'], 'row data check'); + + strictEqual(test.set(1, {name: 'qwe3', id: '123'}), true, 'update existing and non-existing fields'); + deepEqual(test.data.rows[1], ['qwe3', 'rty'], 'row data check'); + + strictEqual(test.set(1, {type: [], name: {}}), true, 'update complex data'); + deepEqual(test.data.rows[1], [ + {}, + [] + ], 'row data check'); +}); + +test('unset', function () { + var db = new jsonDb(); + var test = db.table('test'); + test.init('id', 'name', 'type'); + + strictEqual(test.set(1, []), true, 'empty data'); + strictEqual(Object.keys(test.data.rows).length, 1, 'table rows count'); + strictEqual(test.unset(1), true, 'clear'); + strictEqual(Object.keys(test.data.rows).length, 0, 'table rows count'); +}); + +test('clear', function () { + var db = new jsonDb(); + var test = db.table('test'); + test.init('id', 'name', 'type'); + test.add(1, 'a1', 'b1'); + test.add(2, 'a1', 'b2'); + test.add(3, 'a1', 'b3'); + test.add(4, 'a2', 'b1'); + test.add(5, 'a2', 'b2'); + test.add(6, 'a2', 'b3'); + deepEqual(test.find({}).length, 6, 'check length'); + test.clear(); + deepEqual(test.find({}).length, 0, 'check length'); + deepEqual(test.data.rowIdx, 0, 'index value'); +}); + +test('find', function () { + var db = new jsonDb(); + var test = db.table('test'); + test.init('id', 'name', 'type'); + test.add(1, 'a1', 'b1'); + test.add(2, 'a1', 'b2'); + test.add(3, 'a1', 'b3'); + test.add(4, 'a2', 'b1'); + test.add(5, 'a2', 'b2'); + test.add(6, 'a2', 'b3'); + + deepEqual(test.find().length, 0, 'wrong filter'); + deepEqual(test.find(null).length, 0, 'wrong filter'); + deepEqual(test.find(false).length, 0, 'wrong filter'); + deepEqual(test.find('qwe').length, 0, 'wrong filter'); + deepEqual(test.find({name: 'a0'}).length, 0, 'wrong filter'); + + deepEqual(test.find({}).length, 6, 'filter all'); + deepEqual(test.find({name: 'a1'}).length, 3, 'filter by name'); + deepEqual(test.find({type: 'b1'}).length, 2, 'filter by type'); + deepEqual(test.find({type: 'b1'}).pop(), {id: '4', name: 'a2', type: 'b1'}, 'filter by type last item'); + + deepEqual(test.find({name: 'a1'}, 0).length, 3, 'filter by name'); + deepEqual(test.find({name: 'a1'}, 2).length, 2, 'filter by name'); +}); \ No newline at end of file diff --git a/mag/tests/qunit/qunit-1.13.0.css b/mag/tests/qunit/qunit-1.13.0.css new file mode 100644 index 0000000..26a85d2 --- /dev/null +++ b/mag/tests/qunit/qunit-1.13.0.css @@ -0,0 +1,245 @@ +/*! + * QUnit 1.13.0 + * http://qunitjs.com/ + * + * Copyright 2013 jQuery Foundation and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2014-01-04T17:09Z + */ + +/** Font Family and Sizes */ + +#qunit-tests, #qunit-header, #qunit-banner, #qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult { + font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial, sans-serif; +} + +#qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult, #qunit-tests li { font-size: small; } +#qunit-tests { font-size: smaller; } + + +/** Resets */ + +#qunit-tests, #qunit-header, #qunit-banner, #qunit-userAgent, #qunit-testresult, #qunit-modulefilter { + margin: 0; + padding: 0; +} + + +/** Header */ + +#qunit-header { + padding: 0.5em 0 0.5em 1em; + + color: #8699a4; + background-color: #0d3349; + + font-size: 1.5em; + line-height: 1em; + font-weight: normal; + + border-radius: 5px 5px 0 0; + -moz-border-radius: 5px 5px 0 0; + -webkit-border-top-right-radius: 5px; + -webkit-border-top-left-radius: 5px; +} + +#qunit-header a { + text-decoration: none; + color: #c2ccd1; +} + +#qunit-header a:hover, +#qunit-header a:focus { + color: #fff; +} + +#qunit-testrunner-toolbar label { + display: inline-block; + padding: 0 .5em 0 .1em; +} + +#qunit-banner { + height: 5px; +} + +#qunit-testrunner-toolbar { + padding: 0.5em 0 0.5em 2em; + color: #5E740B; + background-color: #eee; + overflow: hidden; +} + +#qunit-userAgent { + padding: 0.5em 0 0.5em 2.5em; + background-color: #2b81af; + color: #fff; + text-shadow: rgba(0, 0, 0, 0.5) 2px 2px 1px; +} + +#qunit-modulefilter-container { + float: right; +} + +/** Tests: Pass/Fail */ + +#qunit-tests { + list-style-position: inside; +} + +#qunit-tests li { + padding: 0.4em 0.5em 0.4em 2.5em; + border-bottom: 1px solid #fff; + list-style-position: inside; +} + +#qunit-tests.hidepass li.pass, #qunit-tests.hidepass li.running { + display: none; +} + +#qunit-tests li strong { + cursor: pointer; +} + +#qunit-tests li a { + padding: 0.5em; + color: #c2ccd1; + text-decoration: none; +} +#qunit-tests li a:hover, +#qunit-tests li a:focus { + color: #000; +} + +#qunit-tests li .runtime { + float: right; + font-size: smaller; +} + +.qunit-assert-list { + margin-top: 0.5em; + padding: 0.5em; + + background-color: #fff; + + border-radius: 5px; + -moz-border-radius: 5px; + -webkit-border-radius: 5px; +} + +.qunit-collapsed { + display: none; +} + +#qunit-tests table { + border-collapse: collapse; + margin-top: .2em; +} + +#qunit-tests th { + text-align: right; + vertical-align: top; + padding: 0 .5em 0 0; +} + +#qunit-tests td { + vertical-align: top; +} + +#qunit-tests pre { + margin: 0; + white-space: pre-wrap; + word-wrap: break-word; +} + +#qunit-tests del { + background-color: #e0f2be; + color: #374e0c; + text-decoration: none; +} + +#qunit-tests ins { + background-color: #ffcaca; + color: #500; + text-decoration: none; +} + +/*** Test Counts */ + +#qunit-tests b.counts { color: black; } +#qunit-tests b.passed { color: #5E740B; } +#qunit-tests b.failed { color: #710909; } + +#qunit-tests li li { + padding: 5px; + background-color: #fff; + border-bottom: none; + list-style-position: inside; +} + +/*** Passing Styles */ + +#qunit-tests li li.pass { + color: #3c510c; + background-color: #fff; + border-left: 10px solid #C6E746; +} + +#qunit-tests .pass { color: #528CE0; background-color: #D2E0E6; } +#qunit-tests .pass .test-name { color: #366097; } + +#qunit-tests .pass .test-actual, +#qunit-tests .pass .test-expected { color: #999999; } + +#qunit-banner.qunit-pass { background-color: #C6E746; } + +/*** Failing Styles */ + +#qunit-tests li li.fail { + color: #710909; + background-color: #fff; + border-left: 10px solid #EE5757; + white-space: pre; +} + +#qunit-tests > li:last-child { + border-radius: 0 0 5px 5px; + -moz-border-radius: 0 0 5px 5px; + -webkit-border-bottom-right-radius: 5px; + -webkit-border-bottom-left-radius: 5px; +} + +#qunit-tests .fail { color: #000000; background-color: #EE5757; } +#qunit-tests .fail .test-name, +#qunit-tests .fail .module-name { color: #000000; } + +#qunit-tests .fail .test-actual { color: #EE5757; } +#qunit-tests .fail .test-expected { color: green; } + +#qunit-banner.qunit-fail { background-color: #EE5757; } + + +/** Result */ + +#qunit-testresult { + padding: 0.5em 0.5em 0.5em 2.5em; + + color: #2b81af; + background-color: #D2E0E6; + + border-bottom: 1px solid white; +} +#qunit-testresult .module-name { + font-weight: bold; +} + +/** Fixture */ + +#qunit-fixture { + position: absolute; + top: -10000px; + left: -10000px; + width: 1000px; + height: 1000px; +} diff --git a/mag/tests/qunit/qunit-1.13.0.js b/mag/tests/qunit/qunit-1.13.0.js new file mode 100644 index 0000000..c3b8167 --- /dev/null +++ b/mag/tests/qunit/qunit-1.13.0.js @@ -0,0 +1,2210 @@ +/*! + * QUnit 1.13.0 + * http://qunitjs.com/ + * + * Copyright 2013 jQuery Foundation and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2014-01-04T17:09Z + */ + +(function( window ) { + +var QUnit, + assert, + config, + onErrorFnPrev, + testId = 0, + fileName = (sourceFromStacktrace( 0 ) || "" ).replace(/(:\d+)+\)?/, "").replace(/.+\//, ""), + toString = Object.prototype.toString, + hasOwn = Object.prototype.hasOwnProperty, + // Keep a local reference to Date (GH-283) + Date = window.Date, + setTimeout = window.setTimeout, + defined = { + document: typeof window.document !== "undefined", + setTimeout: typeof window.setTimeout !== "undefined", + sessionStorage: (function() { + var x = "qunit-test-string"; + try { + sessionStorage.setItem( x, x ); + sessionStorage.removeItem( x ); + return true; + } catch( e ) { + return false; + } + }()) + }, + /** + * Provides a normalized error string, correcting an issue + * with IE 7 (and prior) where Error.prototype.toString is + * not properly implemented + * + * Based on http://es5.github.com/#x15.11.4.4 + * + * @param {string|Error} error + * @return {string} error message + */ + errorString = function( error ) { + var name, message, + errorString = error.toString(); + if ( errorString.substring( 0, 7 ) === "[object" ) { + name = error.name ? error.name.toString() : "Error"; + message = error.message ? error.message.toString() : ""; + if ( name && message ) { + return name + ": " + message; + } else if ( name ) { + return name; + } else if ( message ) { + return message; + } else { + return "Error"; + } + } else { + return errorString; + } + }, + /** + * Makes a clone of an object using only Array or Object as base, + * and copies over the own enumerable properties. + * + * @param {Object} obj + * @return {Object} New object with only the own properties (recursively). + */ + objectValues = function( obj ) { + // Grunt 0.3.x uses an older version of jshint that still has jshint/jshint#392. + /*jshint newcap: false */ + var key, val, + vals = QUnit.is( "array", obj ) ? [] : {}; + for ( key in obj ) { + if ( hasOwn.call( obj, key ) ) { + val = obj[key]; + vals[key] = val === Object(val) ? objectValues(val) : val; + } + } + return vals; + }; + + +// Root QUnit object. +// `QUnit` initialized at top of scope +QUnit = { + + // call on start of module test to prepend name to all tests + module: function( name, testEnvironment ) { + config.currentModule = name; + config.currentModuleTestEnvironment = testEnvironment; + config.modules[name] = true; + }, + + asyncTest: function( testName, expected, callback ) { + if ( arguments.length === 2 ) { + callback = expected; + expected = null; + } + + QUnit.test( testName, expected, callback, true ); + }, + + test: function( testName, expected, callback, async ) { + var test, + nameHtml = "" + escapeText( testName ) + ""; + + if ( arguments.length === 2 ) { + callback = expected; + expected = null; + } + + if ( config.currentModule ) { + nameHtml = "" + escapeText( config.currentModule ) + ": " + nameHtml; + } + + test = new Test({ + nameHtml: nameHtml, + testName: testName, + expected: expected, + async: async, + callback: callback, + module: config.currentModule, + moduleTestEnvironment: config.currentModuleTestEnvironment, + stack: sourceFromStacktrace( 2 ) + }); + + if ( !validTest( test ) ) { + return; + } + + test.queue(); + }, + + // Specify the number of expected assertions to guarantee that failed test (no assertions are run at all) don't slip through. + expect: function( asserts ) { + if (arguments.length === 1) { + config.current.expected = asserts; + } else { + return config.current.expected; + } + }, + + start: function( count ) { + // QUnit hasn't been initialized yet. + // Note: RequireJS (et al) may delay onLoad + if ( config.semaphore === undefined ) { + QUnit.begin(function() { + // This is triggered at the top of QUnit.load, push start() to the event loop, to allow QUnit.load to finish first + setTimeout(function() { + QUnit.start( count ); + }); + }); + return; + } + + config.semaphore -= count || 1; + // don't start until equal number of stop-calls + if ( config.semaphore > 0 ) { + return; + } + // ignore if start is called more often then stop + if ( config.semaphore < 0 ) { + config.semaphore = 0; + QUnit.pushFailure( "Called start() while already started (QUnit.config.semaphore was 0 already)", null, sourceFromStacktrace(2) ); + return; + } + // A slight delay, to avoid any current callbacks + if ( defined.setTimeout ) { + setTimeout(function() { + if ( config.semaphore > 0 ) { + return; + } + if ( config.timeout ) { + clearTimeout( config.timeout ); + } + + config.blocking = false; + process( true ); + }, 13); + } else { + config.blocking = false; + process( true ); + } + }, + + stop: function( count ) { + config.semaphore += count || 1; + config.blocking = true; + + if ( config.testTimeout && defined.setTimeout ) { + clearTimeout( config.timeout ); + config.timeout = setTimeout(function() { + QUnit.ok( false, "Test timed out" ); + config.semaphore = 1; + QUnit.start(); + }, config.testTimeout ); + } + } +}; + +// We use the prototype to distinguish between properties that should +// be exposed as globals (and in exports) and those that shouldn't +(function() { + function F() {} + F.prototype = QUnit; + QUnit = new F(); + // Make F QUnit's constructor so that we can add to the prototype later + QUnit.constructor = F; +}()); + +/** + * Config object: Maintain internal state + * Later exposed as QUnit.config + * `config` initialized at top of scope + */ +config = { + // The queue of tests to run + queue: [], + + // block until document ready + blocking: true, + + // when enabled, show only failing tests + // gets persisted through sessionStorage and can be changed in UI via checkbox + hidepassed: false, + + // by default, run previously failed tests first + // very useful in combination with "Hide passed tests" checked + reorder: true, + + // by default, modify document.title when suite is done + altertitle: true, + + // when enabled, all tests must call expect() + requireExpects: false, + + // add checkboxes that are persisted in the query-string + // when enabled, the id is set to `true` as a `QUnit.config` property + urlConfig: [ + { + id: "noglobals", + label: "Check for Globals", + tooltip: "Enabling this will test if any test introduces new properties on the `window` object. Stored as query-strings." + }, + { + id: "notrycatch", + label: "No try-catch", + tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging exceptions in IE reasonable. Stored as query-strings." + } + ], + + // Set of all modules. + modules: {}, + + // logging callback queues + begin: [], + done: [], + log: [], + testStart: [], + testDone: [], + moduleStart: [], + moduleDone: [] +}; + +// Initialize more QUnit.config and QUnit.urlParams +(function() { + var i, + location = window.location || { search: "", protocol: "file:" }, + params = location.search.slice( 1 ).split( "&" ), + length = params.length, + urlParams = {}, + current; + + if ( params[ 0 ] ) { + for ( i = 0; i < length; i++ ) { + current = params[ i ].split( "=" ); + current[ 0 ] = decodeURIComponent( current[ 0 ] ); + // allow just a key to turn on a flag, e.g., test.html?noglobals + current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true; + urlParams[ current[ 0 ] ] = current[ 1 ]; + } + } + + QUnit.urlParams = urlParams; + + // String search anywhere in moduleName+testName + config.filter = urlParams.filter; + + // Exact match of the module name + config.module = urlParams.module; + + config.testNumber = parseInt( urlParams.testNumber, 10 ) || null; + + // Figure out if we're running the tests from a server or not + QUnit.isLocal = location.protocol === "file:"; +}()); + +extend( QUnit, { + + config: config, + + // Initialize the configuration options + init: function() { + extend( config, { + stats: { all: 0, bad: 0 }, + moduleStats: { all: 0, bad: 0 }, + started: +new Date(), + updateRate: 1000, + blocking: false, + autostart: true, + autorun: false, + filter: "", + queue: [], + semaphore: 1 + }); + + var tests, banner, result, + qunit = id( "qunit" ); + + if ( qunit ) { + qunit.innerHTML = + "

" + escapeText( document.title ) + "

" + + "

" + + "
" + + "

" + + "
    "; + } + + tests = id( "qunit-tests" ); + banner = id( "qunit-banner" ); + result = id( "qunit-testresult" ); + + if ( tests ) { + tests.innerHTML = ""; + } + + if ( banner ) { + banner.className = ""; + } + + if ( result ) { + result.parentNode.removeChild( result ); + } + + if ( tests ) { + result = document.createElement('p'); + result.id = "qunit-testresult"; + result.className = "result"; + tests.parentNode.insertBefore( result, tests ); + result.innerHTML = "Running...
     "; + } + }, + + // Resets the test setup. Useful for tests that modify the DOM. + /* + DEPRECATED: Use multiple tests instead of resetting inside a test. + Use testStart or testDone for custom cleanup. + This method will throw an error in 2.0, and will be removed in 2.1 + */ + reset: function() { + var fixture = id( "qunit-fixture" ); + if ( fixture ) { + fixture.innerHTML = config.fixture; + } + }, + + // Safe object type checking + is: function( type, obj ) { + return QUnit.objectType( obj ) === type; + }, + + objectType: function( obj ) { + if ( typeof obj === "undefined" ) { + return "undefined"; + } + + // Consider: typeof null === object + if ( obj === null ) { + return "null"; + } + + var match = toString.call( obj ).match(/^\[object\s(.*)\]$/), + type = match && match[1] || ""; + + switch ( type ) { + case "Number": + if ( isNaN(obj) ) { + return "nan"; + } + return "number"; + case "String": + case "Boolean": + case "Array": + case "Date": + case "RegExp": + case "Function": + return type.toLowerCase(); + } + if ( typeof obj === "object" ) { + return "object"; + } + return undefined; + }, + + push: function( result, actual, expected, message ) { + if ( !config.current ) { + throw new Error( "assertion outside test context, was " + sourceFromStacktrace() ); + } + + var output, source, + details = { + module: config.current.module, + name: config.current.testName, + result: result, + message: message, + actual: actual, + expected: expected + }; + + message = escapeText( message ) || ( result ? "okay" : "failed" ); + message = "" + message + ""; + output = message; + + if ( !result ) { + expected = escapeText( QUnit.jsDump.parse(expected) ); + actual = escapeText( QUnit.jsDump.parse(actual) ); + output += ""; + + if ( actual !== expected ) { + output += ""; + output += ""; + } + + source = sourceFromStacktrace(); + + if ( source ) { + details.source = source; + output += ""; + } + + output += "
    Expected:
    " + expected + "
    Result:
    " + actual + "
    Diff:
    " + QUnit.diff( expected, actual ) + "
    Source:
    " + escapeText( source ) + "
    "; + } + + runLoggingCallbacks( "log", QUnit, details ); + + config.current.assertions.push({ + result: !!result, + message: output + }); + }, + + pushFailure: function( message, source, actual ) { + if ( !config.current ) { + throw new Error( "pushFailure() assertion outside test context, was " + sourceFromStacktrace(2) ); + } + + var output, + details = { + module: config.current.module, + name: config.current.testName, + result: false, + message: message + }; + + message = escapeText( message ) || 'error'; + message = "" + message + ""; + output = message; + + output += ""; + + if ( actual ) { + output += ""; + } + + if ( source ) { + details.source = source; + output += ""; + } + + output += "
    Result:
    " + escapeText( actual ) + "
    Source:
    " + escapeText( source ) + "
    "; + + runLoggingCallbacks( "log", QUnit, details ); + + config.current.assertions.push({ + result: false, + message: output + }); + }, + + url: function( params ) { + params = extend( extend( {}, QUnit.urlParams ), params ); + var key, + querystring = "?"; + + for ( key in params ) { + if ( hasOwn.call( params, key ) ) { + querystring += encodeURIComponent( key ) + "=" + + encodeURIComponent( params[ key ] ) + "&"; + } + } + return window.location.protocol + "//" + window.location.host + + window.location.pathname + querystring.slice( 0, -1 ); + }, + + extend: extend, + id: id, + addEvent: addEvent, + addClass: addClass, + hasClass: hasClass, + removeClass: removeClass + // load, equiv, jsDump, diff: Attached later +}); + +/** + * @deprecated: Created for backwards compatibility with test runner that set the hook function + * into QUnit.{hook}, instead of invoking it and passing the hook function. + * QUnit.constructor is set to the empty F() above so that we can add to it's prototype here. + * Doing this allows us to tell if the following methods have been overwritten on the actual + * QUnit object. + */ +extend( QUnit.constructor.prototype, { + + // Logging callbacks; all receive a single argument with the listed properties + // run test/logs.html for any related changes + begin: registerLoggingCallback( "begin" ), + + // done: { failed, passed, total, runtime } + done: registerLoggingCallback( "done" ), + + // log: { result, actual, expected, message } + log: registerLoggingCallback( "log" ), + + // testStart: { name } + testStart: registerLoggingCallback( "testStart" ), + + // testDone: { name, failed, passed, total, runtime } + testDone: registerLoggingCallback( "testDone" ), + + // moduleStart: { name } + moduleStart: registerLoggingCallback( "moduleStart" ), + + // moduleDone: { name, failed, passed, total } + moduleDone: registerLoggingCallback( "moduleDone" ) +}); + +if ( !defined.document || document.readyState === "complete" ) { + config.autorun = true; +} + +QUnit.load = function() { + runLoggingCallbacks( "begin", QUnit, {} ); + + // Initialize the config, saving the execution queue + var banner, filter, i, label, len, main, ol, toolbar, userAgent, val, + urlConfigCheckboxesContainer, urlConfigCheckboxes, moduleFilter, + numModules = 0, + moduleNames = [], + moduleFilterHtml = "", + urlConfigHtml = "", + oldconfig = extend( {}, config ); + + QUnit.init(); + extend(config, oldconfig); + + config.blocking = false; + + len = config.urlConfig.length; + + for ( i = 0; i < len; i++ ) { + val = config.urlConfig[i]; + if ( typeof val === "string" ) { + val = { + id: val, + label: val, + tooltip: "[no tooltip available]" + }; + } + config[ val.id ] = QUnit.urlParams[ val.id ]; + urlConfigHtml += ""; + } + for ( i in config.modules ) { + if ( config.modules.hasOwnProperty( i ) ) { + moduleNames.push(i); + } + } + numModules = moduleNames.length; + moduleNames.sort( function( a, b ) { + return a.localeCompare( b ); + }); + moduleFilterHtml += ""; + + // `userAgent` initialized at top of scope + userAgent = id( "qunit-userAgent" ); + if ( userAgent ) { + userAgent.innerHTML = navigator.userAgent; + } + + // `banner` initialized at top of scope + banner = id( "qunit-header" ); + if ( banner ) { + banner.innerHTML = "" + banner.innerHTML + " "; + } + + // `toolbar` initialized at top of scope + toolbar = id( "qunit-testrunner-toolbar" ); + if ( toolbar ) { + // `filter` initialized at top of scope + filter = document.createElement( 'input' ); + filter.type = "checkbox"; + filter.id = "qunit-filter-pass"; + + addEvent( filter, "click", function() { + var tmp, + ol = id( "qunit-tests" ); + + if ( filter.checked ) { + ol.className = ol.className + " hidepass"; + } else { + tmp = ' ' + ol.className.replace( /[\n\t\r]/g, ' ' ) + ' '; + ol.className = tmp.replace( / hidepass /, ' ' ); + } + if ( defined.sessionStorage ) { + if (filter.checked) { + sessionStorage.setItem( "qunit-filter-passed-tests", "true" ); + } else { + sessionStorage.removeItem( "qunit-filter-passed-tests" ); + } + } + }); + + if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem( "qunit-filter-passed-tests" ) ) { + filter.checked = true; + // `ol` initialized at top of scope + ol = id( "qunit-tests" ); + ol.className = ol.className + " hidepass"; + } + toolbar.appendChild( filter ); + + // `label` initialized at top of scope + label = document.createElement( "label" ); + label.setAttribute( "for", "qunit-filter-pass" ); + label.setAttribute( "title", "Only show tests and assertions that fail. Stored in sessionStorage." ); + label.innerHTML = "Hide passed tests"; + toolbar.appendChild( label ); + + urlConfigCheckboxesContainer = document.createElement('span'); + urlConfigCheckboxesContainer.innerHTML = urlConfigHtml; + urlConfigCheckboxes = urlConfigCheckboxesContainer.getElementsByTagName('input'); + // For oldIE support: + // * Add handlers to the individual elements instead of the container + // * Use "click" instead of "change" + // * Fallback from event.target to event.srcElement + addEvents( urlConfigCheckboxes, "click", function( event ) { + var params = {}, + target = event.target || event.srcElement; + params[ target.name ] = target.checked ? true : undefined; + window.location = QUnit.url( params ); + }); + toolbar.appendChild( urlConfigCheckboxesContainer ); + + if (numModules > 1) { + moduleFilter = document.createElement('span'); + moduleFilter.setAttribute( "id", "qunit-modulefilter-container" ); + moduleFilter.innerHTML = moduleFilterHtml; + addEvent( moduleFilter.lastChild, "change", function() { + var selectBox = moduleFilter.getElementsByTagName("select")[0], + selectedModule = decodeURIComponent(selectBox.options[selectBox.selectedIndex].value); + + window.location = QUnit.url({ + module: ( selectedModule === "" ) ? undefined : selectedModule, + // Remove any existing filters + filter: undefined, + testNumber: undefined + }); + }); + toolbar.appendChild(moduleFilter); + } + } + + // `main` initialized at top of scope + main = id( "qunit-fixture" ); + if ( main ) { + config.fixture = main.innerHTML; + } + + if ( config.autostart ) { + QUnit.start(); + } +}; + +if ( defined.document ) { + addEvent( window, "load", QUnit.load ); +} + +// `onErrorFnPrev` initialized at top of scope +// Preserve other handlers +onErrorFnPrev = window.onerror; + +// Cover uncaught exceptions +// Returning true will suppress the default browser handler, +// returning false will let it run. +window.onerror = function ( error, filePath, linerNr ) { + var ret = false; + if ( onErrorFnPrev ) { + ret = onErrorFnPrev( error, filePath, linerNr ); + } + + // Treat return value as window.onerror itself does, + // Only do our handling if not suppressed. + if ( ret !== true ) { + if ( QUnit.config.current ) { + if ( QUnit.config.current.ignoreGlobalErrors ) { + return true; + } + QUnit.pushFailure( error, filePath + ':' + linerNr ); + } else { + QUnit.test( "global failure", extend( function() { + QUnit.pushFailure( error, filePath + ':' + linerNr ); + }, { validTest: validTest } ) ); + } + return false; + } + + return ret; +}; + +function done() { + config.autorun = true; + + // Log the last module results + if ( config.previousModule ) { + runLoggingCallbacks( "moduleDone", QUnit, { + name: config.previousModule, + failed: config.moduleStats.bad, + passed: config.moduleStats.all - config.moduleStats.bad, + total: config.moduleStats.all + }); + } + delete config.previousModule; + + var i, key, + banner = id( "qunit-banner" ), + tests = id( "qunit-tests" ), + runtime = +new Date() - config.started, + passed = config.stats.all - config.stats.bad, + html = [ + "Tests completed in ", + runtime, + " milliseconds.
    ", + "", + passed, + " assertions of ", + config.stats.all, + " passed, ", + config.stats.bad, + " failed." + ].join( "" ); + + if ( banner ) { + banner.className = ( config.stats.bad ? "qunit-fail" : "qunit-pass" ); + } + + if ( tests ) { + id( "qunit-testresult" ).innerHTML = html; + } + + if ( config.altertitle && defined.document && document.title ) { + // show ✖ for good, ✔ for bad suite result in title + // use escape sequences in case file gets loaded with non-utf-8-charset + document.title = [ + ( config.stats.bad ? "\u2716" : "\u2714" ), + document.title.replace( /^[\u2714\u2716] /i, "" ) + ].join( ' ' ); + } + + // clear own sessionStorage items if all tests passed + if ( config.reorder && defined.sessionStorage && config.stats.bad === 0 ) { + // `key` & `i` initialized at top of scope + for ( i = 0; i < sessionStorage.length; i++ ) { + key = sessionStorage.key( i++ ); + if ( key.indexOf( "qunit-test-" ) === 0 ) { + sessionStorage.removeItem( key ); + } + } + } + + // scroll back to top to show results + if ( window.scrollTo ) { + window.scrollTo(0, 0); + } + + runLoggingCallbacks( "done", QUnit, { + failed: config.stats.bad, + passed: passed, + total: config.stats.all, + runtime: runtime + }); +} + +/** @return Boolean: true if this test should be ran */ +function validTest( test ) { + var include, + filter = config.filter && config.filter.toLowerCase(), + module = config.module && config.module.toLowerCase(), + fullName = (test.module + ": " + test.testName).toLowerCase(); + + // Internally-generated tests are always valid + if ( test.callback && test.callback.validTest === validTest ) { + delete test.callback.validTest; + return true; + } + + if ( config.testNumber ) { + return test.testNumber === config.testNumber; + } + + if ( module && ( !test.module || test.module.toLowerCase() !== module ) ) { + return false; + } + + if ( !filter ) { + return true; + } + + include = filter.charAt( 0 ) !== "!"; + if ( !include ) { + filter = filter.slice( 1 ); + } + + // If the filter matches, we need to honour include + if ( fullName.indexOf( filter ) !== -1 ) { + return include; + } + + // Otherwise, do the opposite + return !include; +} + +// so far supports only Firefox, Chrome and Opera (buggy), Safari (for real exceptions) +// Later Safari and IE10 are supposed to support error.stack as well +// See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack +function extractStacktrace( e, offset ) { + offset = offset === undefined ? 3 : offset; + + var stack, include, i; + + if ( e.stacktrace ) { + // Opera + return e.stacktrace.split( "\n" )[ offset + 3 ]; + } else if ( e.stack ) { + // Firefox, Chrome + stack = e.stack.split( "\n" ); + if (/^error$/i.test( stack[0] ) ) { + stack.shift(); + } + if ( fileName ) { + include = []; + for ( i = offset; i < stack.length; i++ ) { + if ( stack[ i ].indexOf( fileName ) !== -1 ) { + break; + } + include.push( stack[ i ] ); + } + if ( include.length ) { + return include.join( "\n" ); + } + } + return stack[ offset ]; + } else if ( e.sourceURL ) { + // Safari, PhantomJS + // hopefully one day Safari provides actual stacktraces + // exclude useless self-reference for generated Error objects + if ( /qunit.js$/.test( e.sourceURL ) ) { + return; + } + // for actual exceptions, this is useful + return e.sourceURL + ':' + e.line; + } +} +function sourceFromStacktrace( offset ) { + try { + throw new Error(); + } catch ( e ) { + return extractStacktrace( e, offset ); + } +} + +/** + * Escape text for attribute or text content. + */ +function escapeText( s ) { + if ( !s ) { + return ""; + } + s = s + ""; + // Both single quotes and double quotes (for attributes) + return s.replace( /['"<>&]/g, function( s ) { + switch( s ) { + case "'": + return "'"; + case "\"": + return """; + case "<": + return "<"; + case ">": + return ">"; + case "&": + return "&"; + } + }); +} + +function synchronize( callback, last ) { + config.queue.push( callback ); + + if ( config.autorun && !config.blocking ) { + process( last ); + } +} + +function process( last ) { + function next() { + process( last ); + } + var start = new Date().getTime(); + config.depth = config.depth ? config.depth + 1 : 1; + + while ( config.queue.length && !config.blocking ) { + if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) { + config.queue.shift()(); + } else { + setTimeout( next, 13 ); + break; + } + } + config.depth--; + if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) { + done(); + } +} + +function saveGlobal() { + config.pollution = []; + + if ( config.noglobals ) { + for ( var key in window ) { + if ( hasOwn.call( window, key ) ) { + // in Opera sometimes DOM element ids show up here, ignore them + if ( /^qunit-test-output/.test( key ) ) { + continue; + } + config.pollution.push( key ); + } + } + } +} + +function checkPollution() { + var newGlobals, + deletedGlobals, + old = config.pollution; + + saveGlobal(); + + newGlobals = diff( config.pollution, old ); + if ( newGlobals.length > 0 ) { + QUnit.pushFailure( "Introduced global variable(s): " + newGlobals.join(", ") ); + } + + deletedGlobals = diff( old, config.pollution ); + if ( deletedGlobals.length > 0 ) { + QUnit.pushFailure( "Deleted global variable(s): " + deletedGlobals.join(", ") ); + } +} + +// returns a new Array with the elements that are in a but not in b +function diff( a, b ) { + var i, j, + result = a.slice(); + + for ( i = 0; i < result.length; i++ ) { + for ( j = 0; j < b.length; j++ ) { + if ( result[i] === b[j] ) { + result.splice( i, 1 ); + i--; + break; + } + } + } + return result; +} + +function extend( a, b ) { + for ( var prop in b ) { + if ( hasOwn.call( b, prop ) ) { + // Avoid "Member not found" error in IE8 caused by messing with window.constructor + if ( !( prop === "constructor" && a === window ) ) { + if ( b[ prop ] === undefined ) { + delete a[ prop ]; + } else { + a[ prop ] = b[ prop ]; + } + } + } + } + + return a; +} + +/** + * @param {HTMLElement} elem + * @param {string} type + * @param {Function} fn + */ +function addEvent( elem, type, fn ) { + if ( elem.addEventListener ) { + + // Standards-based browsers + elem.addEventListener( type, fn, false ); + } else if ( elem.attachEvent ) { + + // support: IE <9 + elem.attachEvent( "on" + type, fn ); + } else { + + // Caller must ensure support for event listeners is present + throw new Error( "addEvent() was called in a context without event listener support" ); + } +} + +/** + * @param {Array|NodeList} elems + * @param {string} type + * @param {Function} fn + */ +function addEvents( elems, type, fn ) { + var i = elems.length; + while ( i-- ) { + addEvent( elems[i], type, fn ); + } +} + +function hasClass( elem, name ) { + return (' ' + elem.className + ' ').indexOf(' ' + name + ' ') > -1; +} + +function addClass( elem, name ) { + if ( !hasClass( elem, name ) ) { + elem.className += (elem.className ? ' ' : "") + name; + } +} + +function removeClass( elem, name ) { + var set = " " + elem.className + " "; + // Class name may appear multiple times + while ( set.indexOf(" " + name + " ") > -1 ) { + set = set.replace(" " + name + " " , " "); + } + // If possible, trim it for prettiness, but not necessarily + elem.className = typeof set.trim === 'function' ? set.trim() : set.replace(/^\s+|\s+$/g, ""); +} + +function id( name ) { + return defined.document && document.getElementById && document.getElementById( name ); +} + +function registerLoggingCallback( key ) { + return function( callback ) { + config[key].push( callback ); + }; +} + +// Supports deprecated method of completely overwriting logging callbacks +function runLoggingCallbacks( key, scope, args ) { + var i, callbacks; + if ( QUnit.hasOwnProperty( key ) ) { + QUnit[ key ].call(scope, args ); + } else { + callbacks = config[ key ]; + for ( i = 0; i < callbacks.length; i++ ) { + callbacks[ i ].call( scope, args ); + } + } +} + +// from jquery.js +function inArray( elem, array ) { + if ( array.indexOf ) { + return array.indexOf( elem ); + } + + for ( var i = 0, length = array.length; i < length; i++ ) { + if ( array[ i ] === elem ) { + return i; + } + } + + return -1; +} + +function Test( settings ) { + extend( this, settings ); + this.assertions = []; + this.testNumber = ++Test.count; +} + +Test.count = 0; + +Test.prototype = { + init: function() { + var a, b, li, + tests = id( "qunit-tests" ); + + if ( tests ) { + b = document.createElement( "strong" ); + b.innerHTML = this.nameHtml; + + // `a` initialized at top of scope + a = document.createElement( "a" ); + a.innerHTML = "Rerun"; + a.href = QUnit.url({ testNumber: this.testNumber }); + + li = document.createElement( "li" ); + li.appendChild( b ); + li.appendChild( a ); + li.className = "running"; + li.id = this.id = "qunit-test-output" + testId++; + + tests.appendChild( li ); + } + }, + setup: function() { + if ( + // Emit moduleStart when we're switching from one module to another + this.module !== config.previousModule || + // They could be equal (both undefined) but if the previousModule property doesn't + // yet exist it means this is the first test in a suite that isn't wrapped in a + // module, in which case we'll just emit a moduleStart event for 'undefined'. + // Without this, reporters can get testStart before moduleStart which is a problem. + !hasOwn.call( config, "previousModule" ) + ) { + if ( hasOwn.call( config, "previousModule" ) ) { + runLoggingCallbacks( "moduleDone", QUnit, { + name: config.previousModule, + failed: config.moduleStats.bad, + passed: config.moduleStats.all - config.moduleStats.bad, + total: config.moduleStats.all + }); + } + config.previousModule = this.module; + config.moduleStats = { all: 0, bad: 0 }; + runLoggingCallbacks( "moduleStart", QUnit, { + name: this.module + }); + } + + config.current = this; + + this.testEnvironment = extend({ + setup: function() {}, + teardown: function() {} + }, this.moduleTestEnvironment ); + + this.started = +new Date(); + runLoggingCallbacks( "testStart", QUnit, { + name: this.testName, + module: this.module + }); + + /*jshint camelcase:false */ + + + /** + * Expose the current test environment. + * + * @deprecated since 1.12.0: Use QUnit.config.current.testEnvironment instead. + */ + QUnit.current_testEnvironment = this.testEnvironment; + + /*jshint camelcase:true */ + + if ( !config.pollution ) { + saveGlobal(); + } + if ( config.notrycatch ) { + this.testEnvironment.setup.call( this.testEnvironment, QUnit.assert ); + return; + } + try { + this.testEnvironment.setup.call( this.testEnvironment, QUnit.assert ); + } catch( e ) { + QUnit.pushFailure( "Setup failed on " + this.testName + ": " + ( e.message || e ), extractStacktrace( e, 1 ) ); + } + }, + run: function() { + config.current = this; + + var running = id( "qunit-testresult" ); + + if ( running ) { + running.innerHTML = "Running:
    " + this.nameHtml; + } + + if ( this.async ) { + QUnit.stop(); + } + + this.callbackStarted = +new Date(); + + if ( config.notrycatch ) { + this.callback.call( this.testEnvironment, QUnit.assert ); + this.callbackRuntime = +new Date() - this.callbackStarted; + return; + } + + try { + this.callback.call( this.testEnvironment, QUnit.assert ); + this.callbackRuntime = +new Date() - this.callbackStarted; + } catch( e ) { + this.callbackRuntime = +new Date() - this.callbackStarted; + + QUnit.pushFailure( "Died on test #" + (this.assertions.length + 1) + " " + this.stack + ": " + ( e.message || e ), extractStacktrace( e, 0 ) ); + // else next test will carry the responsibility + saveGlobal(); + + // Restart the tests if they're blocking + if ( config.blocking ) { + QUnit.start(); + } + } + }, + teardown: function() { + config.current = this; + if ( config.notrycatch ) { + if ( typeof this.callbackRuntime === "undefined" ) { + this.callbackRuntime = +new Date() - this.callbackStarted; + } + this.testEnvironment.teardown.call( this.testEnvironment, QUnit.assert ); + return; + } else { + try { + this.testEnvironment.teardown.call( this.testEnvironment, QUnit.assert ); + } catch( e ) { + QUnit.pushFailure( "Teardown failed on " + this.testName + ": " + ( e.message || e ), extractStacktrace( e, 1 ) ); + } + } + checkPollution(); + }, + finish: function() { + config.current = this; + if ( config.requireExpects && this.expected === null ) { + QUnit.pushFailure( "Expected number of assertions to be defined, but expect() was not called.", this.stack ); + } else if ( this.expected !== null && this.expected !== this.assertions.length ) { + QUnit.pushFailure( "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run", this.stack ); + } else if ( this.expected === null && !this.assertions.length ) { + QUnit.pushFailure( "Expected at least one assertion, but none were run - call expect(0) to accept zero assertions.", this.stack ); + } + + var i, assertion, a, b, time, li, ol, + test = this, + good = 0, + bad = 0, + tests = id( "qunit-tests" ); + + this.runtime = +new Date() - this.started; + config.stats.all += this.assertions.length; + config.moduleStats.all += this.assertions.length; + + if ( tests ) { + ol = document.createElement( "ol" ); + ol.className = "qunit-assert-list"; + + for ( i = 0; i < this.assertions.length; i++ ) { + assertion = this.assertions[i]; + + li = document.createElement( "li" ); + li.className = assertion.result ? "pass" : "fail"; + li.innerHTML = assertion.message || ( assertion.result ? "okay" : "failed" ); + ol.appendChild( li ); + + if ( assertion.result ) { + good++; + } else { + bad++; + config.stats.bad++; + config.moduleStats.bad++; + } + } + + // store result when possible + if ( QUnit.config.reorder && defined.sessionStorage ) { + if ( bad ) { + sessionStorage.setItem( "qunit-test-" + this.module + "-" + this.testName, bad ); + } else { + sessionStorage.removeItem( "qunit-test-" + this.module + "-" + this.testName ); + } + } + + if ( bad === 0 ) { + addClass( ol, "qunit-collapsed" ); + } + + // `b` initialized at top of scope + b = document.createElement( "strong" ); + b.innerHTML = this.nameHtml + " (" + bad + ", " + good + ", " + this.assertions.length + ")"; + + addEvent(b, "click", function() { + var next = b.parentNode.lastChild, + collapsed = hasClass( next, "qunit-collapsed" ); + ( collapsed ? removeClass : addClass )( next, "qunit-collapsed" ); + }); + + addEvent(b, "dblclick", function( e ) { + var target = e && e.target ? e.target : window.event.srcElement; + if ( target.nodeName.toLowerCase() === 'span' || target.nodeName.toLowerCase() === "b" ) { + target = target.parentNode; + } + if ( window.location && target.nodeName.toLowerCase() === "strong" ) { + window.location = QUnit.url({ testNumber: test.testNumber }); + } + }); + + // `time` initialized at top of scope + time = document.createElement( 'span' ); + time.className = "runtime"; + time.innerHTML = this.runtime + " ms"; + + // `li` initialized at top of scope + li = id( this.id ); + li.className = bad ? "fail" : "pass"; + li.removeChild( li.firstChild ); + a = li.firstChild; + li.appendChild( b ); + li.appendChild( a ); + li.appendChild( time ); + li.appendChild( ol ); + + } else { + for ( i = 0; i < this.assertions.length; i++ ) { + if ( !this.assertions[i].result ) { + bad++; + config.stats.bad++; + config.moduleStats.bad++; + } + } + } + + runLoggingCallbacks( "testDone", QUnit, { + name: this.testName, + module: this.module, + failed: bad, + passed: this.assertions.length - bad, + total: this.assertions.length, + runtime: this.runtime, + // DEPRECATED: this property will be removed in 2.0.0, use runtime instead + duration: this.runtime, + }); + + QUnit.reset(); + + config.current = undefined; + }, + + queue: function() { + var bad, + test = this; + + synchronize(function() { + test.init(); + }); + function run() { + // each of these can by async + synchronize(function() { + test.setup(); + }); + synchronize(function() { + test.run(); + }); + synchronize(function() { + test.teardown(); + }); + synchronize(function() { + test.finish(); + }); + } + + // `bad` initialized at top of scope + // defer when previous test run passed, if storage is available + bad = QUnit.config.reorder && defined.sessionStorage && + +sessionStorage.getItem( "qunit-test-" + this.module + "-" + this.testName ); + + if ( bad ) { + run(); + } else { + synchronize( run, true ); + } + } +}; + +// `assert` initialized at top of scope +// Assert helpers +// All of these must either call QUnit.push() or manually do: +// - runLoggingCallbacks( "log", .. ); +// - config.current.assertions.push({ .. }); +assert = QUnit.assert = { + /** + * Asserts rough true-ish result. + * @name ok + * @function + * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); + */ + ok: function( result, msg ) { + if ( !config.current ) { + throw new Error( "ok() assertion outside test context, was " + sourceFromStacktrace(2) ); + } + result = !!result; + msg = msg || ( result ? "okay" : "failed" ); + + var source, + details = { + module: config.current.module, + name: config.current.testName, + result: result, + message: msg + }; + + msg = "" + escapeText( msg ) + ""; + + if ( !result ) { + source = sourceFromStacktrace( 2 ); + if ( source ) { + details.source = source; + msg += "
    Source:
    " +
    +					escapeText( source ) +
    +					"
    "; + } + } + runLoggingCallbacks( "log", QUnit, details ); + config.current.assertions.push({ + result: result, + message: msg + }); + }, + + /** + * Assert that the first two arguments are equal, with an optional message. + * Prints out both actual and expected values. + * @name equal + * @function + * @example equal( format( "Received {0} bytes.", 2), "Received 2 bytes.", "format() replaces {0} with next argument" ); + */ + equal: function( actual, expected, message ) { + /*jshint eqeqeq:false */ + QUnit.push( expected == actual, actual, expected, message ); + }, + + /** + * @name notEqual + * @function + */ + notEqual: function( actual, expected, message ) { + /*jshint eqeqeq:false */ + QUnit.push( expected != actual, actual, expected, message ); + }, + + /** + * @name propEqual + * @function + */ + propEqual: function( actual, expected, message ) { + actual = objectValues(actual); + expected = objectValues(expected); + QUnit.push( QUnit.equiv(actual, expected), actual, expected, message ); + }, + + /** + * @name notPropEqual + * @function + */ + notPropEqual: function( actual, expected, message ) { + actual = objectValues(actual); + expected = objectValues(expected); + QUnit.push( !QUnit.equiv(actual, expected), actual, expected, message ); + }, + + /** + * @name deepEqual + * @function + */ + deepEqual: function( actual, expected, message ) { + QUnit.push( QUnit.equiv(actual, expected), actual, expected, message ); + }, + + /** + * @name notDeepEqual + * @function + */ + notDeepEqual: function( actual, expected, message ) { + QUnit.push( !QUnit.equiv(actual, expected), actual, expected, message ); + }, + + /** + * @name strictEqual + * @function + */ + strictEqual: function( actual, expected, message ) { + QUnit.push( expected === actual, actual, expected, message ); + }, + + /** + * @name notStrictEqual + * @function + */ + notStrictEqual: function( actual, expected, message ) { + QUnit.push( expected !== actual, actual, expected, message ); + }, + + "throws": function( block, expected, message ) { + var actual, + expectedOutput = expected, + ok = false; + + // 'expected' is optional + if ( typeof expected === "string" ) { + message = expected; + expected = null; + } + + config.current.ignoreGlobalErrors = true; + try { + block.call( config.current.testEnvironment ); + } catch (e) { + actual = e; + } + config.current.ignoreGlobalErrors = false; + + if ( actual ) { + // we don't want to validate thrown error + if ( !expected ) { + ok = true; + expectedOutput = null; + // expected is a regexp + } else if ( QUnit.objectType( expected ) === "regexp" ) { + ok = expected.test( errorString( actual ) ); + // expected is a constructor + } else if ( actual instanceof expected ) { + ok = true; + // expected is a validation function which returns true is validation passed + } else if ( expected.call( {}, actual ) === true ) { + expectedOutput = null; + ok = true; + } + + QUnit.push( ok, actual, expectedOutput, message ); + } else { + QUnit.pushFailure( message, null, "No exception was thrown." ); + } + } +}; + +/** + * @deprecated since 1.8.0 + * Kept assertion helpers in root for backwards compatibility. + */ +extend( QUnit.constructor.prototype, assert ); + +/** + * @deprecated since 1.9.0 + * Kept to avoid TypeErrors for undefined methods. + */ +QUnit.constructor.prototype.raises = function() { + QUnit.push( false, false, false, "QUnit.raises has been deprecated since 2012 (fad3c1ea), use QUnit.throws instead" ); +}; + +/** + * @deprecated since 1.0.0, replaced with error pushes since 1.3.0 + * Kept to avoid TypeErrors for undefined methods. + */ +QUnit.constructor.prototype.equals = function() { + QUnit.push( false, false, false, "QUnit.equals has been deprecated since 2009 (e88049a0), use QUnit.equal instead" ); +}; +QUnit.constructor.prototype.same = function() { + QUnit.push( false, false, false, "QUnit.same has been deprecated since 2009 (e88049a0), use QUnit.deepEqual instead" ); +}; + +// Test for equality any JavaScript type. +// Author: Philippe Rathé +QUnit.equiv = (function() { + + // Call the o related callback with the given arguments. + function bindCallbacks( o, callbacks, args ) { + var prop = QUnit.objectType( o ); + if ( prop ) { + if ( QUnit.objectType( callbacks[ prop ] ) === 'function' ) { + return callbacks[ prop ].apply( callbacks, args ); + } else { + return callbacks[ prop ]; // or undefined + } + } + } + + // the real equiv function + var innerEquiv, + // stack to decide between skip/abort functions + callers = [], + // stack to avoiding loops from circular referencing + parents = [], + parentsB = [], + + getProto = Object.getPrototypeOf || function ( obj ) { + /*jshint camelcase:false */ + return obj.__proto__; + }, + callbacks = (function () { + + // for string, boolean, number and null + function useStrictEquality( b, a ) { + /*jshint eqeqeq:false */ + if ( b instanceof a.constructor || a instanceof b.constructor ) { + // to catch short annotation VS 'new' annotation of a + // declaration + // e.g. var i = 1; + // var j = new Number(1); + return a == b; + } else { + return a === b; + } + } + + return { + "string": useStrictEquality, + "boolean": useStrictEquality, + "number": useStrictEquality, + "null": useStrictEquality, + "undefined": useStrictEquality, + + "nan": function( b ) { + return isNaN( b ); + }, + + "date": function( b, a ) { + return QUnit.objectType( b ) === "date" && a.valueOf() === b.valueOf(); + }, + + "regexp": function( b, a ) { + return QUnit.objectType( b ) === "regexp" && + // the regex itself + a.source === b.source && + // and its modifiers + a.global === b.global && + // (gmi) ... + a.ignoreCase === b.ignoreCase && + a.multiline === b.multiline && + a.sticky === b.sticky; + }, + + // - skip when the property is a method of an instance (OOP) + // - abort otherwise, + // initial === would have catch identical references anyway + 'function': function() { + var caller = callers[callers.length - 1]; + return caller !== Object && typeof caller !== "undefined"; + }, + + "array": function( b, a ) { + var i, j, len, loop, aCircular, bCircular; + + // b could be an object literal here + if ( QUnit.objectType( b ) !== "array" ) { + return false; + } + + len = a.length; + if ( len !== b.length ) { + // safe and faster + return false; + } + + // track reference to avoid circular references + parents.push( a ); + parentsB.push( b ); + for ( i = 0; i < len; i++ ) { + loop = false; + for ( j = 0; j < parents.length; j++ ) { + aCircular = parents[j] === a[i]; + bCircular = parentsB[j] === b[i]; + if ( aCircular || bCircular ) { + if ( a[i] === b[i] || aCircular && bCircular ) { + loop = true; + } else { + parents.pop(); + parentsB.pop(); + return false; + } + } + } + if ( !loop && !innerEquiv(a[i], b[i]) ) { + parents.pop(); + parentsB.pop(); + return false; + } + } + parents.pop(); + parentsB.pop(); + return true; + }, + + "object": function( b, a ) { + /*jshint forin:false */ + var i, j, loop, aCircular, bCircular, + // Default to true + eq = true, + aProperties = [], + bProperties = []; + + // comparing constructors is more strict than using + // instanceof + if ( a.constructor !== b.constructor ) { + // Allow objects with no prototype to be equivalent to + // objects with Object as their constructor. + if ( !(( getProto(a) === null && getProto(b) === Object.prototype ) || + ( getProto(b) === null && getProto(a) === Object.prototype ) ) ) { + return false; + } + } + + // stack constructor before traversing properties + callers.push( a.constructor ); + + // track reference to avoid circular references + parents.push( a ); + parentsB.push( b ); + + // be strict: don't ensure hasOwnProperty and go deep + for ( i in a ) { + loop = false; + for ( j = 0; j < parents.length; j++ ) { + aCircular = parents[j] === a[i]; + bCircular = parentsB[j] === b[i]; + if ( aCircular || bCircular ) { + if ( a[i] === b[i] || aCircular && bCircular ) { + loop = true; + } else { + eq = false; + break; + } + } + } + aProperties.push(i); + if ( !loop && !innerEquiv(a[i], b[i]) ) { + eq = false; + break; + } + } + + parents.pop(); + parentsB.pop(); + callers.pop(); // unstack, we are done + + for ( i in b ) { + bProperties.push( i ); // collect b's properties + } + + // Ensures identical properties name + return eq && innerEquiv( aProperties.sort(), bProperties.sort() ); + } + }; + }()); + + innerEquiv = function() { // can take multiple arguments + var args = [].slice.apply( arguments ); + if ( args.length < 2 ) { + return true; // end transition + } + + return (function( a, b ) { + if ( a === b ) { + return true; // catch the most you can + } else if ( a === null || b === null || typeof a === "undefined" || + typeof b === "undefined" || + QUnit.objectType(a) !== QUnit.objectType(b) ) { + return false; // don't lose time with error prone cases + } else { + return bindCallbacks(a, callbacks, [ b, a ]); + } + + // apply transition with (1..n) arguments + }( args[0], args[1] ) && innerEquiv.apply( this, args.splice(1, args.length - 1 )) ); + }; + + return innerEquiv; +}()); + +/** + * jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | + * http://flesler.blogspot.com Licensed under BSD + * (http://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008 + * + * @projectDescription Advanced and extensible data dumping for Javascript. + * @version 1.0.0 + * @author Ariel Flesler + * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html} + */ +QUnit.jsDump = (function() { + function quote( str ) { + return "\"" + str.toString().replace( /"/g, "\\\"" ) + "\""; + } + function literal( o ) { + return o + ""; + } + function join( pre, arr, post ) { + var s = jsDump.separator(), + base = jsDump.indent(), + inner = jsDump.indent(1); + if ( arr.join ) { + arr = arr.join( "," + s + inner ); + } + if ( !arr ) { + return pre + post; + } + return [ pre, inner + arr, base + post ].join(s); + } + function array( arr, stack ) { + var i = arr.length, ret = new Array(i); + this.up(); + while ( i-- ) { + ret[i] = this.parse( arr[i] , undefined , stack); + } + this.down(); + return join( "[", ret, "]" ); + } + + var reName = /^function (\w+)/, + jsDump = { + // type is used mostly internally, you can fix a (custom)type in advance + parse: function( obj, type, stack ) { + stack = stack || [ ]; + var inStack, res, + parser = this.parsers[ type || this.typeOf(obj) ]; + + type = typeof parser; + inStack = inArray( obj, stack ); + + if ( inStack !== -1 ) { + return "recursion(" + (inStack - stack.length) + ")"; + } + if ( type === "function" ) { + stack.push( obj ); + res = parser.call( this, obj, stack ); + stack.pop(); + return res; + } + return ( type === "string" ) ? parser : this.parsers.error; + }, + typeOf: function( obj ) { + var type; + if ( obj === null ) { + type = "null"; + } else if ( typeof obj === "undefined" ) { + type = "undefined"; + } else if ( QUnit.is( "regexp", obj) ) { + type = "regexp"; + } else if ( QUnit.is( "date", obj) ) { + type = "date"; + } else if ( QUnit.is( "function", obj) ) { + type = "function"; + } else if ( typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined" ) { + type = "window"; + } else if ( obj.nodeType === 9 ) { + type = "document"; + } else if ( obj.nodeType ) { + type = "node"; + } else if ( + // native arrays + toString.call( obj ) === "[object Array]" || + // NodeList objects + ( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item(0) === obj[0] : ( obj.item( 0 ) === null && typeof obj[0] === "undefined" ) ) ) + ) { + type = "array"; + } else if ( obj.constructor === Error.prototype.constructor ) { + type = 'error'; + } else { + type = typeof obj; + } + return type; + }, + separator: function() { + return this.multiline ? this.HTML ? "
    " : "\n" : this.HTML ? " " : " "; + }, + // extra can be a number, shortcut for increasing-calling-decreasing + indent: function( extra ) { + if ( !this.multiline ) { + return ""; + } + var chr = this.indentChar; + if ( this.HTML ) { + chr = chr.replace( /\t/g, " " ).replace( / /g, " " ); + } + return new Array( this.depth + ( extra || 0 ) ).join(chr); + }, + up: function( a ) { + this.depth += a || 1; + }, + down: function( a ) { + this.depth -= a || 1; + }, + setParser: function( name, parser ) { + this.parsers[name] = parser; + }, + // The next 3 are exposed so you can use them + quote: quote, + literal: literal, + join: join, + // + depth: 1, + // This is the list of parsers, to modify them, use jsDump.setParser + parsers: { + window: "[Window]", + document: "[Document]", + error: function(error) { + return "Error(\"" + error.message + "\")"; + }, + unknown: "[Unknown]", + "null": "null", + "undefined": "undefined", + "function": function( fn ) { + var ret = "function", + // functions never have name in IE + name = 'name' in fn ? fn.name : (reName.exec(fn) || [])[1]; + + if ( name ) { + ret += " " + name; + } + ret += "( "; + + ret = [ ret, QUnit.jsDump.parse( fn, "functionArgs" ), "){" ].join( "" ); + return join( ret, QUnit.jsDump.parse(fn,"functionCode" ), "}" ); + }, + array: array, + nodelist: array, + "arguments": array, + object: function( map, stack ) { + /*jshint forin:false */ + var ret = [ ], keys, key, val, i; + QUnit.jsDump.up(); + keys = []; + for ( key in map ) { + keys.push( key ); + } + keys.sort(); + for ( i = 0; i < keys.length; i++ ) { + key = keys[ i ]; + val = map[ key ]; + ret.push( QUnit.jsDump.parse( key, "key" ) + ": " + QUnit.jsDump.parse( val, undefined, stack ) ); + } + QUnit.jsDump.down(); + return join( "{", ret, "}" ); + }, + node: function( node ) { + var len, i, val, + open = QUnit.jsDump.HTML ? "<" : "<", + close = QUnit.jsDump.HTML ? ">" : ">", + tag = node.nodeName.toLowerCase(), + ret = open + tag, + attrs = node.attributes; + + if ( attrs ) { + for ( i = 0, len = attrs.length; i < len; i++ ) { + val = attrs[i].nodeValue; + // IE6 includes all attributes in .attributes, even ones not explicitly set. + // Those have values like undefined, null, 0, false, "" or "inherit". + if ( val && val !== "inherit" ) { + ret += " " + attrs[i].nodeName + "=" + QUnit.jsDump.parse( val, "attribute" ); + } + } + } + ret += close; + + // Show content of TextNode or CDATASection + if ( node.nodeType === 3 || node.nodeType === 4 ) { + ret += node.nodeValue; + } + + return ret + open + "/" + tag + close; + }, + // function calls it internally, it's the arguments part of the function + functionArgs: function( fn ) { + var args, + l = fn.length; + + if ( !l ) { + return ""; + } + + args = new Array(l); + while ( l-- ) { + // 97 is 'a' + args[l] = String.fromCharCode(97+l); + } + return " " + args.join( ", " ) + " "; + }, + // object calls it internally, the key part of an item in a map + key: quote, + // function calls it internally, it's the content of the function + functionCode: "[code]", + // node calls it internally, it's an html attribute value + attribute: quote, + string: quote, + date: quote, + regexp: literal, + number: literal, + "boolean": literal + }, + // if true, entities are escaped ( <, >, \t, space and \n ) + HTML: false, + // indentation unit + indentChar: " ", + // if true, items in a collection, are separated by a \n, else just a space. + multiline: true + }; + + return jsDump; +}()); + +/* + * Javascript Diff Algorithm + * By John Resig (http://ejohn.org/) + * Modified by Chu Alan "sprite" + * + * Released under the MIT license. + * + * More Info: + * http://ejohn.org/projects/javascript-diff-algorithm/ + * + * Usage: QUnit.diff(expected, actual) + * + * QUnit.diff( "the quick brown fox jumped over", "the quick fox jumps over" ) == "the quick brown fox jumped jumps over" + */ +QUnit.diff = (function() { + /*jshint eqeqeq:false, eqnull:true */ + function diff( o, n ) { + var i, + ns = {}, + os = {}; + + for ( i = 0; i < n.length; i++ ) { + if ( !hasOwn.call( ns, n[i] ) ) { + ns[ n[i] ] = { + rows: [], + o: null + }; + } + ns[ n[i] ].rows.push( i ); + } + + for ( i = 0; i < o.length; i++ ) { + if ( !hasOwn.call( os, o[i] ) ) { + os[ o[i] ] = { + rows: [], + n: null + }; + } + os[ o[i] ].rows.push( i ); + } + + for ( i in ns ) { + if ( hasOwn.call( ns, i ) ) { + if ( ns[i].rows.length === 1 && hasOwn.call( os, i ) && os[i].rows.length === 1 ) { + n[ ns[i].rows[0] ] = { + text: n[ ns[i].rows[0] ], + row: os[i].rows[0] + }; + o[ os[i].rows[0] ] = { + text: o[ os[i].rows[0] ], + row: ns[i].rows[0] + }; + } + } + } + + for ( i = 0; i < n.length - 1; i++ ) { + if ( n[i].text != null && n[ i + 1 ].text == null && n[i].row + 1 < o.length && o[ n[i].row + 1 ].text == null && + n[ i + 1 ] == o[ n[i].row + 1 ] ) { + + n[ i + 1 ] = { + text: n[ i + 1 ], + row: n[i].row + 1 + }; + o[ n[i].row + 1 ] = { + text: o[ n[i].row + 1 ], + row: i + 1 + }; + } + } + + for ( i = n.length - 1; i > 0; i-- ) { + if ( n[i].text != null && n[ i - 1 ].text == null && n[i].row > 0 && o[ n[i].row - 1 ].text == null && + n[ i - 1 ] == o[ n[i].row - 1 ]) { + + n[ i - 1 ] = { + text: n[ i - 1 ], + row: n[i].row - 1 + }; + o[ n[i].row - 1 ] = { + text: o[ n[i].row - 1 ], + row: i - 1 + }; + } + } + + return { + o: o, + n: n + }; + } + + return function( o, n ) { + o = o.replace( /\s+$/, "" ); + n = n.replace( /\s+$/, "" ); + + var i, pre, + str = "", + out = diff( o === "" ? [] : o.split(/\s+/), n === "" ? [] : n.split(/\s+/) ), + oSpace = o.match(/\s+/g), + nSpace = n.match(/\s+/g); + + if ( oSpace == null ) { + oSpace = [ " " ]; + } + else { + oSpace.push( " " ); + } + + if ( nSpace == null ) { + nSpace = [ " " ]; + } + else { + nSpace.push( " " ); + } + + if ( out.n.length === 0 ) { + for ( i = 0; i < out.o.length; i++ ) { + str += "" + out.o[i] + oSpace[i] + ""; + } + } + else { + if ( out.n[0].text == null ) { + for ( n = 0; n < out.o.length && out.o[n].text == null; n++ ) { + str += "" + out.o[n] + oSpace[n] + ""; + } + } + + for ( i = 0; i < out.n.length; i++ ) { + if (out.n[i].text == null) { + str += "" + out.n[i] + nSpace[i] + ""; + } + else { + // `pre` initialized at top of scope + pre = ""; + + for ( n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++ ) { + pre += "" + out.o[n] + oSpace[n] + ""; + } + str += " " + out.n[i].text + nSpace[i] + pre; + } + } + } + + return str; + }; +}()); + +// For browser, export only select globals +if ( typeof window !== "undefined" ) { + extend( window, QUnit.constructor.prototype ); + window.QUnit = QUnit; +} + +// For CommonJS environments, export everything +if ( typeof module !== "undefined" && module.exports ) { + module.exports = QUnit; +} + + +// Get a reference to the global object, like window in browsers +}( (function() { + return this; +})() )); diff --git a/mag/tests/storage.js b/mag/tests/storage.js new file mode 100644 index 0000000..fbca6df --- /dev/null +++ b/mag/tests/storage.js @@ -0,0 +1,37 @@ +'use strict'; + +module('stbStorage API'); + +test('methods availability', function () { + strictEqual(typeof stbStorage.length, 'number', 'stbStorage.count'); + strictEqual(typeof stbStorage.clear, 'function', 'stbStorage.clear'); + strictEqual(typeof stbStorage.key, 'function', 'stbStorage.keys'); + strictEqual(typeof stbStorage.getItem, 'function', 'stbStorage.getItem'); + strictEqual(typeof stbStorage.setItem, 'function', 'stbStorage.setItem'); + strictEqual(typeof stbStorage.removeItem, 'function', 'stbStorage.removeItem'); +}); + +test('general', function () { + stbStorage.clear(); + strictEqual(stbStorage.length, 0, 'count after clear'); + strictEqual(stbStorage.getItem('missingKey'), null, 'request missing key'); + strictEqual(stbStorage.removeItem('missingKey'), undefined, 'remove missing key'); + strictEqual(stbStorage.length, 0, 'count empty'); + + stbStorage.setItem('key1', 'val1'); + strictEqual(stbStorage.length, 1, 'count'); + strictEqual(stbStorage.getItem('key1'), 'val1', 'request key value'); + stbStorage.setItem('key1', 'val2'); + strictEqual(stbStorage.getItem('key1'), 'val2', 'updated key value'); + strictEqual(stbStorage.removeItem('key1'), undefined, 'remove the key'); + strictEqual(stbStorage.removeItem('key1'), undefined, 'remove the key again'); + strictEqual(stbStorage.length, 0, 'count'); + stbStorage.setItem('key1', 128); + strictEqual(stbStorage.getItem('key1'), '128', 'numeric key value'); + stbStorage.setItem('key2', true); + strictEqual(stbStorage.getItem('key2'), 'true', 'boolean key value'); + stbStorage.clear(); + stbStorage.setItem('key2', true); + strictEqual(stbStorage.key(0), 'key2', 'get key name by index'); + strictEqual(stbStorage.key(8), null, 'get key name by wrong index'); +}); diff --git a/mag/tests/winapi.js b/mag/tests/winapi.js new file mode 100644 index 0000000..1b95cff --- /dev/null +++ b/mag/tests/winapi.js @@ -0,0 +1,30 @@ +'use strict'; + +module('Windows API'); + +test('methods availability', function () { + strictEqual(typeof stbWindowMgr.windowInit, 'function', 'stbWindowMgr.windowInit'); + strictEqual(typeof stbWindowMgr.windowAttr, 'function', 'stbWindowMgr.windowAttr'); + strictEqual(typeof stbWindowMgr.windowList, 'function', 'stbWindowMgr.windowList'); + strictEqual(typeof stbWindowMgr.windowInfo, 'function', 'stbWindowMgr.windowInfo'); + strictEqual(typeof stbWindowMgr.windowShow, 'function', 'stbWindowMgr.windowShow'); + strictEqual(typeof stbWindowMgr.windowHide, 'function', 'stbWindowMgr.windowHide'); + strictEqual(typeof stbWindowMgr.windowLoad, 'function', 'stbWindowMgr.windowLoad'); + strictEqual(typeof stbWindowMgr.windowClose, 'function', 'stbWindowMgr.windowClose'); + strictEqual(typeof stbWindowMgr.windowActive, 'function', 'stbWindowMgr.windowActive'); + strictEqual(typeof stbWebWindow.windowId, 'function', 'stbWebWindow.windowId'); + strictEqual(typeof stbWebWindow.messageSend, 'function', 'stbWebWindow.messageSend'); + strictEqual(typeof stbWebWindow.messageBroadcast, 'function', 'stbWebWindow.messageBroadcast'); +}); + +// global event +var stbEvent = { + onEvent : function(data){}, + event : 0, + onMessage: function ( windowId, message, data ) { + + }, + onBroadcastMessage: function ( windowId, message, data ) { + + } +}; diff --git a/mag/tools/build.gettext.cmd b/mag/tools/build.gettext.cmd new file mode 100644 index 0000000..8a18171 --- /dev/null +++ b/mag/tools/build.gettext.cmd @@ -0,0 +1,74 @@ +REM building ... + +node gettext.js -s "../public/app/ibman/lang/ru.po ../system/access.control/lang/ru.po" +node gettext.js -s "../public/app/ibman/lang/de.po ../system/access.control/lang/de.po" +node gettext.js -s "../public/app/ibman/lang/bg.po ../system/access.control/lang/bg.po" +node gettext.js -s "../public/app/ibman/lang/uk.po ../system/access.control/lang/uk.po" +node gettext.js -s "../public/app/ibman/lang/tr.po ../system/access.control/lang/tr.po" +node gettext.js -s "../public/app/ibman/lang/el.po ../system/access.control/lang/el.po" + +node gettext.js -s "../public/app/dlman/lang/ru.po ../system/access.control/lang/ru.po" +node gettext.js -s "../public/app/dlman/lang/de.po ../system/access.control/lang/de.po" +node gettext.js -s "../public/app/dlman/lang/bg.po ../system/access.control/lang/bg.po" +node gettext.js -s "../public/app/dlman/lang/uk.po ../system/access.control/lang/uk.po" +node gettext.js -s "../public/app/dlman/lang/es.po ../system/access.control/lang/es.po" +node gettext.js -s "../public/app/dlman/lang/tr.po ../system/access.control/lang/tr.po" +node gettext.js -s "../public/app/dlman/lang/el.po ../system/access.control/lang/el.po" + +node gettext.js -s "../public/app/pvr/lang/ru.po" +node gettext.js -s "../public/app/pvr/lang/de.po" +node gettext.js -s "../public/app/pvr/lang/bg.po" +node gettext.js -s "../public/app/pvr/lang/uk.po" +node gettext.js -s "../public/app/pvr/lang/es.po" +node gettext.js -s "../public/app/pvr/lang/tr.po" +node gettext.js -s "../public/app/pvr/lang/el.po" + +node gettext.js -s "../public/app/help/lang/ru.po" +node gettext.js -s "../public/app/help/lang/de.po" +node gettext.js -s "../public/app/help/lang/bg.po" +node gettext.js -s "../public/app/help/lang/uk.po" +node gettext.js -s "../public/app/help/lang/es.po" +node gettext.js -s "../public/app/help/lang/tr.po" +node gettext.js -s "../public/app/help/lang/el.po" + +node gettext.js -s "../public/portal/master_settings/lang/ru.po" +node gettext.js -s "../public/portal/master_settings/lang/de.po" +node gettext.js -s "../public/portal/master_settings/lang/bg.po" +node gettext.js -s "../public/portal/master_settings/lang/uk.po" +node gettext.js -s "../public/portal/master_settings/lang/es.po" +node gettext.js -s "../public/portal/master_settings/lang/tr.po" +node gettext.js -s "../public/portal/master_settings/lang/el.po" + +node gettext.js -s "../public/portal/lang/ru.po ../system/updater/lang/ru.po ../system/access.control/lang/ru.po" +node gettext.js -s "../public/portal/lang/de.po ../system/updater/lang/de.po ../system/access.control/lang/de.po" +node gettext.js -s "../public/portal/lang/bg.po ../system/updater/lang/bg.po ../system/access.control/lang/bg.po" +node gettext.js -s "../public/portal/lang/uk.po ../system/updater/lang/uk.po ../system/access.control/lang/uk.po" +node gettext.js -s "../public/portal/lang/es.po ../system/updater/lang/es.po ../system/access.control/lang/es.po" +node gettext.js -s "../public/portal/lang/tr.po ../system/updater/lang/tr.po ../system/access.control/lang/tr.po" +node gettext.js -s "../public/portal/lang/el.po ../system/updater/lang/el.po ../system/access.control/lang/el.po" + +node gettext.js -s "../system/pages/loader/lang/ru.po ../system/access.control/lang/ru.po" +node gettext.js -s "../system/pages/loader/lang/de.po ../system/access.control/lang/de.po" +node gettext.js -s "../system/pages/loader/lang/bg.po ../system/access.control/lang/bg.po" +node gettext.js -s "../system/pages/loader/lang/uk.po ../system/access.control/lang/uk.po" +node gettext.js -s "../system/pages/loader/lang/es.po ../system/access.control/lang/es.po" +node gettext.js -s "../system/pages/loader/lang/tr.po ../system/access.control/lang/tr.po" +node gettext.js -s "../system/pages/loader/lang/el.po ../system/access.control/lang/el.po" + +node gettext.js -s "../system/settings/lang/ru.po ../system/updater/lang/ru.po ../system/access.control/lang/ru.po" +node gettext.js -s "../system/settings/lang/de.po ../system/updater/lang/de.po ../system/access.control/lang/de.po" +node gettext.js -s "../system/settings/lang/bg.po ../system/updater/lang/bg.po ../system/access.control/lang/bg.po" +node gettext.js -s "../system/settings/lang/uk.po ../system/updater/lang/uk.po ../system/access.control/lang/uk.po" +node gettext.js -s "../system/settings/lang/es.po ../system/updater/lang/es.po ../system/access.control/lang/es.po" +node gettext.js -s "../system/settings/lang/tr.po ../system/updater/lang/tr.po ../system/access.control/lang/tr.po" +node gettext.js -s "../system/settings/lang/el.po ../system/updater/lang/el.po ../system/access.control/lang/el.po" + +node gettext.js -s "../system/updater/lang/ru.po" +node gettext.js -s "../system/updater/lang/de.po" +node gettext.js -s "../system/updater/lang/bg.po" +node gettext.js -s "../system/updater/lang/uk.po" +node gettext.js -s "../system/updater/lang/es.po" +node gettext.js -s "../system/updater/lang/tr.po" +node gettext.js -s "../system/updater/lang/el.po" + +pause \ No newline at end of file diff --git a/mag/tools/build.gettext.sh b/mag/tools/build.gettext.sh new file mode 100644 index 0000000..f9eaf43 --- /dev/null +++ b/mag/tools/build.gettext.sh @@ -0,0 +1,73 @@ +#!/usr/bin/env bash + +nodejs gettext.js -s "../public/app/ibman/lang/ru.po ../system/access.control/lang/ru.po" +nodejs gettext.js -s "../public/app/ibman/lang/de.po ../system/access.control/lang/de.po" +nodejs gettext.js -s "../public/app/ibman/lang/bg.po ../system/access.control/lang/bg.po" +nodejs gettext.js -s "../public/app/ibman/lang/uk.po ../system/access.control/lang/uk.po" +nodejs gettext.js -s "../public/app/ibman/lang/es.po ../system/access.control/lang/es.po" +nodejs gettext.js -s "../public/app/ibman/lang/tr.po ../system/access.control/lang/tr.po" +nodejs gettext.js -s "../public/app/ibman/lang/el.po ../system/access.control/lang/el.po" + +nodejs gettext.js -s "../public/app/dlman/lang/ru.po ../system/access.control/lang/ru.po" +nodejs gettext.js -s "../public/app/dlman/lang/de.po ../system/access.control/lang/de.po" +nodejs gettext.js -s "../public/app/dlman/lang/bg.po ../system/access.control/lang/bg.po" +nodejs gettext.js -s "../public/app/dlman/lang/uk.po ../system/access.control/lang/uk.po" +nodejs gettext.js -s "../public/app/dlman/lang/es.po ../system/access.control/lang/es.po" +nodejs gettext.js -s "../public/app/dlman/lang/tr.po ../system/access.control/lang/tr.po" +nodejs gettext.js -s "../public/app/dlman/lang/el.po ../system/access.control/lang/el.po" + +nodejs gettext.js -s "../public/app/pvr/lang/ru.po" +nodejs gettext.js -s "../public/app/pvr/lang/de.po" +nodejs gettext.js -s "../public/app/pvr/lang/bg.po" +nodejs gettext.js -s "../public/app/pvr/lang/uk.po" +nodejs gettext.js -s "../public/app/pvr/lang/es.po" +nodejs gettext.js -s "../public/app/pvr/lang/tr.po" +nodejs gettext.js -s "../public/app/pvr/lang/el.po" + +nodejs gettext.js -s "../public/app/help/lang/ru.po" +nodejs gettext.js -s "../public/app/help/lang/de.po" +nodejs gettext.js -s "../public/app/help/lang/bg.po" +nodejs gettext.js -s "../public/app/help/lang/uk.po" +nodejs gettext.js -s "../public/app/help/lang/es.po" +nodejs gettext.js -s "../public/app/help/lang/tr.po" +nodejs gettext.js -s "../public/app/help/lang/el.po" + +nodejs gettext.js -s "../public/portal/master_settings/lang/ru.po" +nodejs gettext.js -s "../public/portal/master_settings/lang/de.po" +nodejs gettext.js -s "../public/portal/master_settings/lang/bg.po" +nodejs gettext.js -s "../public/portal/master_settings/lang/uk.po" +nodejs gettext.js -s "../public/portal/master_settings/lang/es.po" +nodejs gettext.js -s "../public/portal/master_settings/lang/tr.po" +nodejs gettext.js -s "../public/portal/master_settings/lang/el.po" + +nodejs gettext.js -s "../public/portal/lang/ru.po ../system/updater/lang/ru.po ../system/access.control/lang/ru.po" +nodejs gettext.js -s "../public/portal/lang/de.po ../system/updater/lang/de.po ../system/access.control/lang/de.po" +nodejs gettext.js -s "../public/portal/lang/bg.po ../system/updater/lang/bg.po ../system/access.control/lang/bg.po" +nodejs gettext.js -s "../public/portal/lang/uk.po ../system/updater/lang/uk.po ../system/access.control/lang/uk.po" +nodejs gettext.js -s "../public/portal/lang/es.po ../system/updater/lang/es.po ../system/access.control/lang/es.po" +nodejs gettext.js -s "../public/portal/lang/tr.po ../system/updater/lang/tr.po ../system/access.control/lang/tr.po" +nodejs gettext.js -s "../public/portal/lang/el.po ../system/updater/lang/el.po ../system/access.control/lang/el.po" + +nodejs gettext.js -s "../system/pages/loader/lang/ru.po ../system/access.control/lang/ru.po" +nodejs gettext.js -s "../system/pages/loader/lang/de.po ../system/access.control/lang/de.po" +nodejs gettext.js -s "../system/pages/loader/lang/bg.po ../system/access.control/lang/bg.po" +nodejs gettext.js -s "../system/pages/loader/lang/uk.po ../system/access.control/lang/uk.po" +nodejs gettext.js -s "../system/pages/loader/lang/es.po ../system/access.control/lang/es.po" +nodejs gettext.js -s "../system/pages/loader/lang/tr.po ../system/access.control/lang/tr.po" +nodejs gettext.js -s "../system/pages/loader/lang/el.po ../system/access.control/lang/el.po" + +nodejs gettext.js -s "../system/settings/lang/ru.po ../system/updater/lang/ru.po ../system/access.control/lang/ru.po" +nodejs gettext.js -s "../system/settings/lang/de.po ../system/updater/lang/de.po ../system/access.control/lang/de.po" +nodejs gettext.js -s "../system/settings/lang/bg.po ../system/updater/lang/bg.po ../system/access.control/lang/bg.po" +nodejs gettext.js -s "../system/settings/lang/uk.po ../system/updater/lang/uk.po ../system/access.control/lang/uk.po" +nodejs gettext.js -s "../system/settings/lang/es.po ../system/updater/lang/es.po ../system/access.control/lang/es.po" +nodejs gettext.js -s "../system/settings/lang/tr.po ../system/updater/lang/tr.po ../system/access.control/lang/tr.po" +nodejs gettext.js -s "../system/settings/lang/el.po ../system/updater/lang/el.po ../system/access.control/lang/el.po" + +nodejs gettext.js -s "../system/updater/lang/ru.po" +nodejs gettext.js -s "../system/updater/lang/de.po" +nodejs gettext.js -s "../system/updater/lang/bg.po" +nodejs gettext.js -s "../system/updater/lang/uk.po" +nodejs gettext.js -s "../system/updater/lang/es.po" +nodejs gettext.js -s "../system/updater/lang/tr.po" +nodejs gettext.js -s "../system/updater/lang/el.po" diff --git a/mag/tools/build.help.cmd b/mag/tools/build.help.cmd new file mode 100644 index 0000000..12a9853 --- /dev/null +++ b/mag/tools/build.help.cmd @@ -0,0 +1,5 @@ +REM building ... + +node gethelp.js + +pause \ No newline at end of file diff --git a/mag/tools/build.help.sh b/mag/tools/build.help.sh new file mode 100644 index 0000000..b136e47 --- /dev/null +++ b/mag/tools/build.help.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash + +nodejs gethelp.js diff --git a/mag/tools/build.release.cmd b/mag/tools/build.release.cmd new file mode 100644 index 0000000..113d789 --- /dev/null +++ b/mag/tools/build.release.cmd @@ -0,0 +1,5 @@ +REM building ... + +node release.js --src ".." --dst "../mini" + +pause \ No newline at end of file diff --git a/mag/tools/build.release.sh b/mag/tools/build.release.sh new file mode 100644 index 0000000..3b4c460 --- /dev/null +++ b/mag/tools/build.release.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash + +nodejs release.js --src ".." --dst "../mini" diff --git a/mag/tools/gethelp.js b/mag/tools/gethelp.js new file mode 100644 index 0000000..615711f --- /dev/null +++ b/mag/tools/gethelp.js @@ -0,0 +1,48 @@ +var DEFAULT_URL = "http://stbhelp.iptv.infomir.com.ua/HelpGenerator.php?relative_path=pages", + file; + +var program = require('commander'), + request = require('request'), + fs = require('fs'), + wrench = require('wrench'), + admzip = require('adm-zip'), + path = require('path'); + +// console colors +var red = '\u001b[31m', + bold = '\u001b[1m', + cyan = '\u001b[36m', + green = '\u001b[32m', + reset = '\u001b[0m'; + +// CLI init +program.version('0.1') + .option('-d, --dst [PATH]', 'destination directory for the help [../public/app/help/pages]', '../public/app/help/pages') + .option('-d, --src [PATH]', 'download url for the help archive [' + DEFAULT_URL + ']', DEFAULT_URL) + .parse(process.argv); + +// Normalize +program.dst = path.resolve(program.dst); + +console.log(green + 'ok\t' + reset + 'prepared the destination directory'); +// prepare +wrench.rmdirSyncRecursive(program.dst, true); +wrench.mkdirSyncRecursive(program.dst); + +var zip_path = program.dst + path.sep + "help.zip", + out = fs.createWriteStream(zip_path), + zip; + +request(program.src, {timeout: 5 * 60* 1000}) + .pipe(out) + .on("close", function () { + console.log(green + 'ok\t' + reset + "archive downloaded"); + console.log(green + 'ok\t' + reset + "start unpacking"); + zip = new admzip(zip_path); + zip.extractAllTo(program.dst, true); + console.log(green + 'ok\t' + reset + "archive unpacked"); + fs.unlink(zip_path, function (err) { + if (err) throw err; + console.log(green + 'ok\t' + reset + 'archive successfully removed'); + }); + }); diff --git a/mag/tools/gettext.js b/mag/tools/gettext.js new file mode 100644 index 0000000..19a19ce --- /dev/null +++ b/mag/tools/gettext.js @@ -0,0 +1,101 @@ +/** + * Module to convert gettext po file to js representation + * @author Stanislav Kalashnik + * @edited Igor Kopanev + */ + +var program = require('commander'), + pofile = require('pofile'), + path = require('path'), + fs = require('fs'); + +// console colors +var red = '\u001b[31m', + bold = '\u001b[1m', + cyan = '\u001b[36m', + green = '\u001b[32m', + reset = '\u001b[0m'; + +function list( str ){ + return str.split(' '); +} + +// CLI init +program.version('0.1') + .option('-f, --file [path]', 'gettext destination file') + .option('-s, --sources ', 'gettext po files', list) + .parse(process.argv); + +// the po files is given +if ( !program.sources || !Array.isArray(program.sources) ) { console.log('Not enough parameters!'); return; } + +var jsFile = program.file, + count = 0, + items = {}, + result = [ + '/**', + ' * automatically generated gettext localization dictionary', + ' * do not edit manually, correction will be lost' + ], + itemsSorted = {}, + itemsSum = 0, + fuzzyCount = 0, + keyList, overwritten; + + +// proceed all given po files +program.sources.forEach(function ( poFile ) { + // absolute path + poFile = path.resolve(poFile.trim()); + // get localization + var po = pofile.parse(fs.readFileSync(poFile, {encoding: 'utf8'})); + // dump name + console.log(cyan + 'file:\t' + reset + poFile + '\t' + green + po.items.length + reset); + + // apply for the first po file + if ( count === 0 ) { + jsFile = jsFile || (path.dirname(poFile) + path.sep + path.basename(poFile, '.po') + '.js'); + result.push(' * @name ' + po.headers['Project-Id-Version']); + result.push(' * @language ' + po.headers['Language']); + result.push(' */'); + } + count++; + + // fill items + po.items.forEach(function ( item ) { + // skip commented + if ( item.obsolete === true ) { + return; + } + + if ( item.flags.fuzzy ) { + fuzzyCount++; + } + + // find duplicates + if ( items[item.msgid] && items[item.msgid] !== item.msgstr[0] ) { + console.log(red + '\toverwritten: ' + reset + item.msgid + ' (old: "' + items[item.msgid] + '" new: "' + item.msgstr[0] + '")'); + } + items[item.msgid] = item.msgstr[0]; + }); + itemsSum = itemsSum + po.items.length; +}); + +keyList = Object.keys(items); +overwritten = itemsSum - keyList.length; +// sorting by key names +keyList.sort().forEach(function ( key ) { + if ( itemsSorted[key] ) { + console.log('\toverwritten:' + key); + } + if ( items[key] && items[key].length > 0 ) { + itemsSorted[key] = items[key]; + } +}); +result.push('gettext.load(' + JSON.stringify(itemsSorted, null, 4) + ');'); + +// and save +console.log(cyan + 'build:\t' + reset + bold + jsFile + '\t' + green + keyList.length + reset + (fuzzyCount ? red : green) + '\tfuzzy:' + fuzzyCount + reset + (overwritten ? ' (total overwritten: ' + overwritten + ')' : '') + '\n'); + +// store js file +fs.writeFileSync(jsFile, result.join('\n'), {encoding:'utf8'}); diff --git a/mag/tools/help-generator/HelpGenerator.php b/mag/tools/help-generator/HelpGenerator.php new file mode 100644 index 0000000..ec45105 --- /dev/null +++ b/mag/tools/help-generator/HelpGenerator.php @@ -0,0 +1,220 @@ +open($destination, ZIPARCHIVE::CREATE)) { + return false; + } + + $source = str_replace('\\', '/', realpath($source)); + + if (is_dir($source) === true) + { + $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST); + + foreach ($files as $file) + { + $file = str_replace('\\', '/', $file); + + // Ignore "." and ".." folders + if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) ) + continue; + + $file = realpath($file); + + if (is_dir($file) === true) + { + $zip->addEmptyDir(str_replace($source . '/', '', $file . '/')); + } + else if (is_file($file) === true) + { + $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file)); + } + } + } + else if (is_file($source) === true) + { + $zip->addFromString(basename($source), file_get_contents($source)); + } + + return $zip->close(); +} + +class HelpGenerator{ + function __construct($config){ + $this->config = $config; + $this->help_dir = TEMP_DIR."/help"; + $this->pages_dir = $this->config['savedir']."/pages"; + } + + function parseFile($dir, $name){ + $pages = array(); + if (is_dir($dir.'/'.$name) && is_file($file = $dir.'/'.$name.'.txt')){ + if ($file = fopen($file,'r')){ + while(!feof($file)) { + $line = fgets($file); + //if ($res = preg_match_all('/\|\s*\[\[.+\]\]\s*\|\s*\[\[.+:(\w+)\s*\|\s*(.*)\s*\]\]\s*\|\s*(.+)\s*\|/', $line, $media)){ + if ($res = preg_match_all('/\|.*{{.+}}.*\|\s*\[\[.+:(\w+)\s*\|\s*(.*)\s*\]\]\s*\|\s*(.+)\s*\|/', $line, $media)){ + $page = array( + "key" => trim($media[1][0]), + "title" => trim($media[2][0]), + "annotation" => trim($media[3][0]) + ); + if (is_dir($dir.'/'.$name.'/'.$page["key"])){ + $page['data'] = $this->parseFile($dir.'/'.$name, $page["key"]); + } + $pages[] = $page; + } + } + fclose($file); + } + } + return $pages; + } + + function renderFile($file){ + $this->parser = new Doku_Parser(); + $this->parser->Handler = new Doku_Handler(); + + $this->parser->addMode('listblock',new Doku_Parser_Mode_ListBlock()); + $this->parser->addMode('preformatted',new Doku_Parser_Mode_Preformatted()); + $this->parser->addMode('notoc',new Doku_Parser_Mode_NoToc()); + $this->parser->addMode('header',new Doku_Parser_Mode_Header()); + $this->parser->addMode('table',new Doku_Parser_Mode_Table()); + + $formats = array ( + 'strong', 'emphasis', 'underline', 'monospace', + 'subscript', 'superscript', 'deleted', + ); + + foreach ( $formats as $format ) { + $this->parser->addMode($format,new Doku_Parser_Mode_Formatting($format)); + } + + $this->parser->addMode('linebreak',new Doku_Parser_Mode_Linebreak()); + $this->parser->addMode('footnote',new Doku_Parser_Mode_Footnote()); + $this->parser->addMode('hr',new Doku_Parser_Mode_HR()); + + $this->parser->addMode('internallink',new Doku_Parser_Mode_InternalLink()); + $this->parser->addMode('externallink',new Doku_Parser_Mode_ExternalLink()); + + $this->parser->addMode('unformatted',new Doku_Parser_Mode_Unformatted()); + $this->parser->addMode('code',new Doku_Parser_Mode_Code()); + $this->parser->addMode('file',new Doku_Parser_Mode_File()); + $this->parser->addMode('quote',new Doku_Parser_Mode_Quote()); + + $this->parser->addMode('multiplyentity',new Doku_Parser_Mode_MultiplyEntity()); + $this->parser->addMode('quotes',new Doku_Parser_Mode_Quotes()); + $this->parser->addMode('media',new Doku_Parser_Mode_Media()); + $this->parser->addMode('eol',new Doku_Parser_Mode_Eol()); + $doc = file_get_contents($file); + $instructions = $this->parser->parse($doc); + $Renderer = new Doku_Renderer_XHTML(); + foreach ( $instructions as $instruction ) { + call_user_func_array(array($Renderer, $instruction[0]),$instruction[1]); + } + return $Renderer->doc; + } + + function updateImages($html, $path){ + $level = substr_count($path, "/"); + if ($_GET['relative_path']){ + $client_path = $_GET['relative_path'].'/'.$path.'/'; + } + for ($i=0, $relative = ""; $i < $level; $i++) { + $relative .= "../"; + } + + //if ($res = preg_match_all('/?/i', $html, $media)){ + if ($res = preg_match_all('/]*src=[\'"]{1}([^\'"]*[:|=]([^\'"]*))[\'"]{1}[^>]*\/>?/i', $html, $media)){ + foreach ($media[1] as $key => $src) { + $image_url = $relative.'images/'.$media[2][$key]; + $html = str_replace($src, $client_path.$image_url, $html); +// print("getBaseURL = ".getBaseURL().$src."\n"); +// print("HTTP_HOST = "."http://".$_SERVER['HTTP_HOST'].$src."\n"); +// print(DEFAULT_URL.$src); +// dump("http://".$_SERVER['HTTP_HOST'].$src, "HOST:"); + file_put_contents($this->help_dir.'/'.$path.'/'.$image_url, file_get_contents("http://".$_SERVER['HTTP_HOST'].$src)); +// file_put_contents($this->help_dir.'/'.$path.'/'.$image_url, file_get_contents(DEFAULT_URL.$src)); + } + } + return $html; + } + + function generatePart($pages, $path, $relative){ + foreach ($pages as $page) { + $part = $relative ? $relative.'/'.$page['key'] : $page['key']; + if ($page['data']){ + mkdir($this->help_dir.'/'.$path.'/'.$part, 0777, true); + $this->generatePart($page['data'], $path, $part); + }else{ + $html = $this->renderFile($this->pages_dir.'/'.$path.'/'.$this->config['start'].'/'.$part.'.txt'); + $html = $this->updateImages($html, $path.'/'.$relative); + file_put_contents($this->help_dir.'/'.$path.'/'.$part.'.html', $html); + } + } + } + + function prepareTmp(){ + delTree(TEMP_DIR); + mkdir($this->help_dir, 0777, true); + } + + function generate(){ + $languages = explode(" ", $this->config['plugin']['translation']['translations']); + //dump($languages); + $pages = array(); + foreach ($languages as $language) { + if (is_dir($directory = $this->pages_dir.'/'.$language)){ + //dump($language); + $pages = $this->parseFile($directory, $this->config['start']); + //dump($pages); + mkdir($this->help_dir.'/'.$language.'/images', 0777, true); + $this->generatePart($pages, $language, ''); + file_put_contents($this->help_dir.'/'.$language.'/pages.json', json_encode($pages)); + } + } + } + + function createArchive($zip){ + Zip($this->help_dir, $zip); + } + + function redirectToZip($zip){ + header("HTTP/1.1 200 OK"); + header("Location: $zip"); + } +} + +$Generator = new HelpGenerator($conf); +$Generator->prepareTmp(); +$Generator->generate(); + +$zip = TEMP_DIR.'/help.zip'; +$Generator->createArchive($zip); +$Generator->redirectToZip($zip); diff --git a/mag/tools/help-generator/aceeditor/action.php b/mag/tools/help-generator/aceeditor/action.php new file mode 100644 index 0000000..f067dd4 --- /dev/null +++ b/mag/tools/help-generator/aceeditor/action.php @@ -0,0 +1,96 @@ +register_hook('DOKUWIKI_STARTED', 'AFTER', + $this, 'handle_dokuwiki_started'); + $controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', + $this, 'handle_tpl_metaheader_output'); + } + + public function handle_dokuwiki_started(Doku_Event $event, $param) { + global $INFO, $JSINFO; + $wraplimit = trim($this->getConf('wraplimit')); + $xmltags = $this->getConf('xmltags'); + $xmltags = ($xmltags ? explode(',', $xmltags) : array()); + $JSINFO['plugin_aceeditor'] = array( + 'default' => $this->getConf('default'), + 'highlight' => $this->getConf('highlight'), + 'wraplimit' => $wraplimit ? (int) $wraplimit : null, + 'colortheme' => $this->getConf('colortheme'), + 'latex' => $this->getConf('latex'), + 'markdown' => $this->getConf('markdown'), + 'mdpage' => substr($INFO['id'], -3) == '.md', + 'xmltags' => $xmltags, + ); + } + + public function handle_tpl_metaheader_output(Doku_Event $event, $param) { + global $ACT; + + if (!in_array($ACT, array('edit', 'create', 'source', 'preview', + 'locked', 'draft', 'recover'))) { + return; + } + + if (!$this->has_jquery() and $this->getConf('loadjquery')) { + $jqueryurl = '//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js'; + $this->link_script($event, $jqueryurl); + $this->include_script($event, '$.noConflict();'); + } + + if (file_exists(DOKU_INC.'lib/plugins/aceeditor/build.js')) { + $this->link_script($event, DOKU_BASE.'lib/plugins/aceeditor/build.js'); + } else { + $this->link_script($event, DOKU_BASE.'lib/plugins/aceeditor/vendor/require.js'); + $this->link_script($event, DOKU_BASE.'lib/plugins/aceeditor/scripts/init.js'); + } + + // Workaround for conflict with syntaxhighlighter3 plugin + $this->include_script($event, 'window.require = undefined;'); + } + + public function has_jquery() { + $version = getVersionData(); + $date = str_replace('-', '', $version['date']); + return (int) $date > 20110525; + } + + private function include_script($event, $code) { + $event->data['script'][] = array( + 'type' => 'text/javascript', + 'charset' => 'utf-8', + '_data' => $code, + ); + } + + private function link_script($event, $url) { + $event->data['script'][] = array( + 'type' => 'text/javascript', + 'charset' => 'utf-8', + 'src' => $url, + ); + } +} diff --git a/mag/tools/help-generator/readme.txt b/mag/tools/help-generator/readme.txt new file mode 100644 index 0000000..aca14a7 --- /dev/null +++ b/mag/tools/help-generator/readme.txt @@ -0,0 +1,13 @@ +Файл ложится в корневую директорию Dokuwiki. + +Требует установленый языковой плагин в Dokuwiki. +Требует права на запись в папку Dokuwiki так как создает в ней временную директорию для своих нужд. + +Для работы генератора достаточно обратиться к нему по http и в ответ он отдаст архив с готовыой справкой. + +Так же необходимо добавить обозначение нового языка в поле "Список поддерживаемых языков " +http://stbhelp.iptv.infomir.com.ua/doku.php?id=start&do=admin&page=config + +Рядом с этой папкой должна появиться новая для нового языка +79.142.197.72 +/var/www/stbhelp.iptv.infomir.com.ua/data/pages/ru \ No newline at end of file diff --git a/mag/tools/http.server.cmd b/mag/tools/http.server.cmd new file mode 100644 index 0000000..7cf69b9 --- /dev/null +++ b/mag/tools/http.server.cmd @@ -0,0 +1 @@ +node http.server.js \ No newline at end of file diff --git a/mag/tools/http.server.js b/mag/tools/http.server.js new file mode 100644 index 0000000..b3499d7 --- /dev/null +++ b/mag/tools/http.server.js @@ -0,0 +1,14 @@ +/** + * HTTP static file server + * @author Stanislav Kalashnik + */ + +'use strict'; + +var files = new (require('node-static')).Server(require('path').join(__dirname, '/..')); + +require('http').createServer(function (request, response) { + request.addListener('end', function () { + files.serve(request, response); + }).resume(); +}).listen(8080); diff --git a/mag/tools/models.js b/mag/tools/models.js new file mode 100644 index 0000000..bb88f00 --- /dev/null +++ b/mag/tools/models.js @@ -0,0 +1,69 @@ +/** + * + * @author Aleynikov Boris . + */ + +var path = require('path'), + fs = require('fs'), + configPath = path.join(process.cwd(), '..', 'public', 'config.js'), + + // + configuration = {}, + PATH_IMG_PUBLIC ='', + PATH_SYSTEM = '' + ; + +Array.prototype.shuffle = function () { + var n = this.length, + i, tmp; + while ( n-- ) { + i = Math.floor(n * Math.random()); + tmp = this[i]; + this[i] = this[n]; + this[n] = tmp; + + } + return this; +}; + +function extend (target, source, override) { + var _target = (override === false ? extend({}, target) : target || {}); + for (var prop in source) { + if ( typeof _target[prop] === 'object' && typeof source[prop] === 'object' && !Array.isArray(_target[prop]) && !Array.isArray(source[prop]) ) { + _target[prop] = extend(_target[prop], source[prop], override); + } else { + _target[prop] = source[prop]; + } + } + return _target; +} + +function getCurrentLanguage () { + return 'en'; +} + +fs.readFile(configPath, 'utf8', function ( error, data ) { + var copy, + idx = data.indexOf('var menu = {'), + codeText = data.slice(idx); + + idx = codeText.indexOf('config = extend(config, models[gSTB.GetDeviceModelExt()]);'); + + codeText = codeText.slice(0, idx); + + + eval(codeText); + + + for ( model in models ) { + copy = JSON.parse(JSON.stringify(config)); + models[model] = extend(copy, models[model]); + console.log(model + ' ' + models[model].logoImagePath); + } + + fs.writeFileSync('models.json', JSON.stringify(models, null, 4)); + console.log('Write to models.json'); + + + +}); diff --git a/mag/tools/package.json b/mag/tools/package.json new file mode 100644 index 0000000..8d9eb34 --- /dev/null +++ b/mag/tools/package.json @@ -0,0 +1,28 @@ +{ + "name": "portal-tools", + "version": "0.1.0", + "description": "command-line utils for the stb portal management", + "keywords": [ + "stb", + "portal", + "command", + "utils" + ], + "author": "Stanislav Kalashnik ", + "repository": {}, + "scripts": { + "test": "echo \"no test specified\"" + }, + "readme": "", + "dependencies": { + "adm-zip": "0.4.x", + "cheerio": "0.12.0", + "commander": "2.6.*", + "pofile": "0.2.*", + "node-static": "0.7.x", + "request": "2.51.x", + "uglify-js": "2.4.x", + "wrench": "1.5.x", + "clean-css": "2.2.x" + } +} diff --git a/mag/tools/readme.md b/mag/tools/readme.md new file mode 100644 index 0000000..e6dbe19 --- /dev/null +++ b/mag/tools/readme.md @@ -0,0 +1,14 @@ +gettext.js - NodeJS скрипт генерации js файлов на основании gettext po файлов + пример вызова: + node gettext.js -f "../public/app/dlman/lang/ru.po" + получение справки: + node gettext.js --help + +build.gettext.cmd - скрипт автоматической генерации js файлов на основании gettext po файлов для всего проекта + вызывается без параметров + +release.js - NodeJS скрипт сборки релиза с вычленением всех зависимостей и склейки в общий файл для каждого html файла + пример вызова (пути по умолчанию): + node release.js + пример вызова (пути в явном виде): + node release.js -s "../../current_portal_path" -d "../../new_minified_version" \ No newline at end of file diff --git a/mag/tools/release.js b/mag/tools/release.js new file mode 100644 index 0000000..c9cba1f --- /dev/null +++ b/mag/tools/release.js @@ -0,0 +1,153 @@ +/** + * Module to prepare minimized and compressed version of page dependence files + * @author Stanislav Kalashnik + */ + +//'use strict'; + +var program = require('commander'), + cheerio = require('cheerio'), + wrench = require('wrench'), + uglify = require('uglify-js'), + path = require('path'), + cleanCss = new (require('clean-css'))({noAdvanced:true, noRebase:true}), + fs = require('fs'), + exec = require('child_process').execSync, + gitHash = fs.existsSync(path.join(__dirname, '..', '.git')) && exec('git rev-parse HEAD').toString().trim(); + +// console colors +var red = '\u001b[31m', + bold = '\u001b[1m', + cyan = '\u001b[36m', + green = '\u001b[32m', + reset = '\u001b[0m'; + +// all used js files +var jsUsedList = {}; + +// CLI init +program.version('0.1') + .option('-s, --src [PATH]', 'source directory with files to proceed [..]', '..') + .option('-d, --dst [PATH]', 'destination directory for the result build [../mini]', '..' + path.sep + 'mini') + .parse(process.argv); + +// the po file is given +if ( !program.src || typeof program.src !== 'string' || + !program.dst || typeof program.dst !== 'string' ) { console.log('Not enough parameters!'); return; } + +// normalize +program.src = path.resolve(program.src); +program.dst = path.resolve(program.dst); +// report +console.log(cyan + 'src:\t' + reset + bold + program.src + reset); +console.log(cyan + 'dst:\t' + reset + bold + program.dst + reset + "\n"); + +// prepare +wrench.rmdirSyncRecursive(program.dst, true); +wrench.mkdirSyncRecursive(program.dst); +// report +console.log(green + 'ok\t' + reset + 'prepared the destination directory'); + +// dirs +wrench.copyDirSyncRecursive(program.src + path.sep + 'public', program.dst + path.sep + 'public'); +wrench.copyDirSyncRecursive(program.src + path.sep + 'system', program.dst + path.sep + 'system'); +// files +fs.writeFileSync(program.dst + path.sep + 'index.html', fs.readFileSync(program.src + path.sep + 'index.html', {encoding:'utf8'}), {encoding:'utf8'}); +fs.writeFileSync(program.dst + path.sep + 'services.html', fs.readFileSync(program.src + path.sep + 'services.html', {encoding:'utf8'}), {encoding:'utf8'}); +fs.writeFileSync(program.dst + path.sep + 'rules.js', fs.readFileSync(program.src + path.sep + 'rules.js', {encoding:'utf8'}), {encoding:'utf8'}); +// report +console.log(green + 'ok\t' + reset + 'cloned the source directory to the destination');/**/ +console.log(green + 'ok\t' + reset + 'cleaning gettext localization files'); + +// remove all po files +walk(program.dst, '.po').forEach(function(item){ + fs.unlinkSync(item); +}); + +// recursively read directories contents +// and get all html files +walk(program.dst, '.html').forEach(function(item){ + var htmlFile = fs.readFileSync(item, {encoding:'utf8'}); + var jsName = path.dirname(item) + path.sep + path.basename(item, '.html') + '.min.js'; + var jsData = []; + var scripts = []; + // screen resolution correction + htmlFile = htmlFile.replace(/WINDOW_HEIGHT/g, 'screen.height'); + htmlFile = htmlFile.replace(/WINDOW_WIDTH/g, 'screen.width'); + // parse + var $ = cheerio.load(htmlFile, {ignoreWhitespace:false, xmlMode:false}); + // find and remove scripts + $('script').each(function(){ + // only in case of include + if ( $(this).attr('src') !== undefined && $(this).attr('src') !== 'rules.js' ) { + var src = path.normalize(path.dirname(item) + path.sep + $(this).attr('src')); + jsUsedList[src] = true; + scripts.push(src); + $(this).remove(); + } + }); + // report + console.log(green + 'ok\t' + reset + 'processed: ' + bold + path.relative(program.dst, item) + reset); + // add one general + if ( scripts.length > 0 ) { + scripts.forEach(function(script){ + console.log('\t\tscript: ' + path.relative(program.dst, script)); + jsData.push(fs.readFileSync(script, {encoding:'utf8'}).trim()); + }); + $('head').append('\n\t\n'); + fs.writeFileSync(jsName, uglify.minify(jsData.join('\n\n\n'), {fromString:true, mangle:false}).code, {encoding:'utf8'}); + } + htmlFile = $.html(); + // resave + fs.writeFileSync(item, htmlFile, {encoding:'utf8'}); +}); + +// clear all used js files +for ( var name in jsUsedList ) if ( jsUsedList.hasOwnProperty(name) ) fs.unlinkSync(name); +// gstb +fs.unlinkSync(program.dst + path.sep + 'system' + path.sep + 'gstb.js'); +console.log(green + 'ok\t' + reset + 'cleared all used js files'); + +console.log(green + 'ok\t' + reset + 'prepare to compile language files'); +// recursively read directories contents +// and get all js files to minimize +walk(program.dst, '.js').forEach(function(item){ + if ( item.indexOf('.min.js') === -1 && item.indexOf('rules.js') === -1 ) { + fs.writeFileSync( + item, + uglify.minify(fs.readFileSync(item, {encoding:'utf8'}), {fromString:true, mangle:false}).code, + {encoding:'utf8'} + ); + } +}); + + +console.log(green + 'ok\t' + reset + 'prepare to minify css files'); +// minify css files +walk(program.dst, '.css').forEach(function(item){ + fs.writeFileSync( + item, + cleanCss.minify(fs.readFileSync(item, {encoding:'utf8'})), + {encoding:'utf8'} + ); +}); + + +// save build info +fs.writeFileSync(program.dst + path.sep + 'info.json', JSON.stringify({ + time: (new Date()).toUTCString(), + hash: gitHash +}, null, '\t'), {encoding:'utf8'}); + + +function walk ( dir, ext ) { + var results = []; + var list = fs.readdirSync(dir); + list.forEach(function ( file ) { + file = dir + path.sep + file; + var stat = fs.statSync(file); + if ( stat && stat.isDirectory() ) results = results.concat(walk(file, ext)); + else if ( path.extname(file) === ext ) results.push(file); + }); + return results; +} diff --git a/mag/tools/stb-proxy/client.js b/mag/tools/stb-proxy/client.js new file mode 100644 index 0000000..f64ff35 --- /dev/null +++ b/mag/tools/stb-proxy/client.js @@ -0,0 +1,110 @@ +/** + * STB Proxy desktop browser (client) part + * @constructor + * @author Stanislav Kalashnik + */ +function proxyClient () { + + /** + * proxy instance configuration + * @namespace + */ + var config = { + /** node.js server address */ + host : '127.0.0.1', + + /** http server port */ + port : 8800, + + /** session name */ + name : 'anonymous', + + /** cached url for posting requests */ + urlPost : null, + + /** cached url for info collecting */ + urlInfo : null + }; + + // single ajax object for performance + var xhr = new XMLHttpRequest(); + + /** + * Prepares the connection + * @param {Object} options set of initialization parameters (host, port, name, urlPost, urlInfo) + */ + this.init = function ( options ) { + // validate and iterate input + if ( options ) for ( var name in options ) { + // rewrite defaults + if ( options.hasOwnProperty(name) ) config[name] = options[name]; + } + // cache final request urls + config.urlPost = 'http://' + config.host + ':' + config.port + '/' + config.name; + config.urlInfo = 'http://' + config.host + ':' + config.port + '/info/' + config.name; + }; + + /** + * Sends a sync request to the STB device from the desktop browser + * @param {Object} data JSON data to send + * @return {*} execution result from the STB + */ + this.send = function ( data ) { + // mandatory init check + if ( !config.urlPost ) return false; + // prepare + var time = +new Date(), + response; + // make request + xhr.open('post', config.urlPost, false); + xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8'); + xhr.send(JSON.stringify(data)); + // proceed the result + try { + response = JSON.parse(xhr.responseText); + } catch ( e ) { + response = {error:e}; + } + // detailed report + console.groupCollapsed('%c%s\t%c%d/%d ms', + 'color:' + (response.error ? 'red' : 'green'), data.method || data.code || 'unhandled STB call', + 'color:#aaa;font-weight:normal', response.time || 0, +new Date() - time); + console.log(data); + console.log(response.error || response.data); + console.groupEnd(); + // ready + return response.data; + }; + + /** + * Wrapper to send a line of js code to eval on the STB device + * @param {string} code javascript source code to execute on the device + * @return {*} execution result from the STB + */ + this.eval = function ( code ) { + return this.send({type:'eval', code:code}); + }; + + /** + * Wrapper to send one function of js code with arguments to eval on the STB device + * @param {string} method javascript function name (like "gSTB.Debug") + * @param {Array} params list of the function arguments + * @return {*} execution result from the STB + */ + this.call = function ( method, params ) { + return this.send({type:'call', method:method, params:params}); + }; + + /** + * Gets the detailed info about the current connection + * @return {{active:Boolean, count:Number}|{active:Boolean}|Boolean} + */ + this.info = function () { + // mandatory init check + if ( !config.urlInfo ) return false; + // make request + xhr.open('get', config.urlInfo, false); + xhr.send(); + return JSON.parse(xhr.responseText || false); + }; +} diff --git a/mag/tools/stb-proxy/server.js b/mag/tools/stb-proxy/server.js new file mode 100644 index 0000000..76f2b7e --- /dev/null +++ b/mag/tools/stb-proxy/server.js @@ -0,0 +1,84 @@ +/** + * STB Proxy device (server) side + * @constructor + * @author Stanislav Kalashnik + */ +function ProxyServer () { + + /** + * proxy instance configuration + * @namespace + */ + var config = { + /** node.js server address */ + host : '127.0.0.1', + + /** websocket server port */ + port : 8900, + + /** session name */ + name : 'anonymous' + }; + + /** + * Prepares the connection + * @param {Object} options set of initialization parameters (host, port, name) + */ + this.init = function ( options ) { + // validate and iterate input + if ( options ) for ( var name in options ) { + // rewrite defaults + if ( options.hasOwnProperty(name) ) config[name] = options[name]; + } + + // establish the connection + config.socket = new WebSocket('ws://' + config.host + ':' + config.port + '/' + config.name); + + // event hook + config.socket.onopen = function(){ + console.log('socket.onopen', config.name); + }; + + // event hook + config.socket.onclose = function(){ + console.log('socket.onclose', config.name); + }; + + // message from a desktop browser + config.socket.onmessage = function ( message ) { + console.log('socket.onmessage', config.name); + // prepare + var result = {time:+new Date()}, + request; + // proceed the message + try { + request = JSON.parse(message.data || false); + // valid incoming request + if ( request && ['call', 'eval'].indexOf(request.type) !== -1 ) { + // exec types + if ( request.type === 'call' ) { + result.data = eval(request.method).apply(window, request.params); + } else if ( request.type === 'eval' ) { + result.data = eval(request.code); + } + } else { + result.error = 'invalid incoming request'; + } + } catch ( e ) { + console.log(e); + result.error = e; + } + // time taken + result.time = +new Date() - result.time; + // wrap and send back + config.socket.send(JSON.stringify(result)); + } + }; + + /** + * Finish the connection + */ + this.close = function () { + config.socket.close(); + } +} diff --git a/mag/tools/stb-proxy/start.html b/mag/tools/stb-proxy/start.html new file mode 100644 index 0000000..5e631db --- /dev/null +++ b/mag/tools/stb-proxy/start.html @@ -0,0 +1,44 @@ + + + + Debug entry point + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + + \ No newline at end of file diff --git a/mag/tools/stb-proxy/start.js b/mag/tools/stb-proxy/start.js new file mode 100644 index 0000000..963d6fb --- /dev/null +++ b/mag/tools/stb-proxy/start.js @@ -0,0 +1,96 @@ +/** + * STB Proxy server node.js part + * handles all requests between desktop browser (client) and server (stb device) + * @author Stanislav Kalashnik + */ + +// globals +var WebSocketServer = require('ws').Server, + wsPool = require('./wspool.js'), + http = require('http'), + fs = require('fs'); + +// connection ports +var portHttp = 8800, // http server + portWss = 8900; // websocket server + +// files allowed to be served +var fileList = ['client.js', 'server.js']; + + +// WebSocket server creation +wss = new WebSocketServer({port:portWss}); +wss.on('connection', function(socket) { + // new awaiting instance of WebSocket in the pool + wsPool.add(socket.upgradeReq.url.slice(1), socket); +}); +console.log('port %d accepts WebSocket connections', portWss); + + +// simple http listener +http.createServer(function(request, response){ + console.log('http\t%s\t%s', request.method, request.url); + // prepare request query + var query = request.url.slice(1).split('/'); + + switch ( request.method ) { + + // simple serve info/file requests + case 'GET': + // first param holds the command name + switch ( query[0] ) { + // serving files + case 'file': + // one of the allowed files + if ( fileList.indexOf(query[1]) !== -1 ) { + response.writeHead(200, {'Content-Type':'application/javascript; charset=utf-8'}); + response.end(fs.readFileSync(query[1])); + } + break; + // get connection info + case 'info': + //var wsItem = wsList.get(query[1]); + response.writeHead(200, {'Content-Type':'application/json; charset=utf-8'}); + response.end(JSON.stringify(wsPool.info(query[1]))); + break; + // show help page + default: + // not valid url or root + response.writeHead(200, {'Content-Type':'text/html; charset=utf-8'}); + response.end(fs.readFileSync('start.html')); + } + break; + + // security info call + case 'OPTIONS': + //TODO: investigate why doesn't work + response.writeHead(200, { + 'Access-Control-Allow-Origin' : '*', + 'Access-Control-Allow-Credentials' : 'true', + 'Access-Control-Allow-Methods' : 'POST, GET, OPTIONS', + 'Access-Control-Allow-Headers' : 'content-type', + 'Access-Control-Max-Age' : 1800 + }); + response.end(); + break; + + // accept connections from desktop clients + case 'POST': + var post = ''; + // append all chunks + request.on('data', function(data){ post += data; }); + // everything is ready to send to the STB + request.on('end', function(){ + // make a call + if ( !wsPool.send(query[0], post, response) ) { + // no available connections so close + response.end(JSON.stringify({error:'no connections'})); + } + }); + break; + + default: + response.end('wrong request!'); + } +}).listen(portHttp); +console.log('port %d accepts HTTP connections\n', portHttp); diff --git a/mag/tools/stb-proxy/tests/client.a.html b/mag/tools/stb-proxy/tests/client.a.html new file mode 100644 index 0000000..150d6cf --- /dev/null +++ b/mag/tools/stb-proxy/tests/client.a.html @@ -0,0 +1,20 @@ + + + + client.a + + + + + + + \ No newline at end of file diff --git a/mag/tools/stb-proxy/tests/client.b.html b/mag/tools/stb-proxy/tests/client.b.html new file mode 100644 index 0000000..316670c --- /dev/null +++ b/mag/tools/stb-proxy/tests/client.b.html @@ -0,0 +1,20 @@ + + + + client.b + + + + + + + \ No newline at end of file diff --git a/mag/tools/stb-proxy/tests/server.a.html b/mag/tools/stb-proxy/tests/server.a.html new file mode 100644 index 0000000..766e277 --- /dev/null +++ b/mag/tools/stb-proxy/tests/server.a.html @@ -0,0 +1,20 @@ + + + + server.a + + + + + + + \ No newline at end of file diff --git a/mag/tools/stb-proxy/tests/server.b.html b/mag/tools/stb-proxy/tests/server.b.html new file mode 100644 index 0000000..9bc65d7 --- /dev/null +++ b/mag/tools/stb-proxy/tests/server.b.html @@ -0,0 +1,20 @@ + + + + server.b + + + + + + + \ No newline at end of file diff --git a/mag/tools/stb-proxy/wspool.js b/mag/tools/stb-proxy/wspool.js new file mode 100644 index 0000000..448ddbe --- /dev/null +++ b/mag/tools/stb-proxy/wspool.js @@ -0,0 +1,109 @@ +/** + * WebSocket pool + * wraps all the work with ws instances + * @author Stanislav Kalashnik + */ + +// named WebSocket list +var pool = {}; + +// exports the wrapper object +module.exports = { + + /** + * New WebSocket creation + * @param {string} name unique identifier for session + * @param {Object} socket websocket resource + * @return {boolean} true if was deleted successfully + */ + add : function ( name, socket ) { + var self = this; + // check input + if ( name && socket ) { + console.log('ws\tINIT\t[%s]\tconnection', name); + + // main data structure + pool[name] = { + socket : socket, + time : Math.round(+new Date()/1000), + count : 0, + active : true + }; + + // disable link on close + pool[name].socket.on('close', function() { + self.remove(name); + }); + + // await for an answer + pool[name].socket.on('message', function(message) { + // has link to talk back + if ( pool[name].response ) { + console.log('ws\tGET\t[%s]\tmessage\t%s', name, message); + pool[name].response.end(message); + } + }); + return true; + } + // failure + console.log('ws\tINIT\t[%s]\tfail to connect (wrong name or link)', name); + return false; + }, + + /** + * Clear resources on WebSocket deletion + * @param {string} name session name + * @return {boolean} true if was deleted successfully + */ + remove : function ( name ) { + // valid connection + if ( name in pool ) { + console.log('ws\tEXIT\t[%s]\tclose', name); + return delete pool[name]; + } + // failure + console.log('ws\tDEL\t[%s]\tfail to remove (invalid connection)', name); + return false; + }, + + /** + * Detailed information of the named WebSocket instance + * @param {string} name session name + * @return {{active:Boolean, count:Number}|{active:Boolean}} + */ + info : function ( name ) { + // valid connection + if ( name in pool ) { + return { + active : pool[name].active, + count : pool[name].count + }; + } + // failure + return {active:false}; + }, + + /** + * + * @param {string} name session name + * @param {string} data post data from browser to STB server + * @param {ServerResponse} response link to HTTP response object to send back data + * @return {boolean} true if was send successfully + */ + send : function ( name, data, response ) { + // valid connection + if ( name in pool && pool[name].active ) { + console.log('ws\tSEND\t[%s]\tmessage\t%s', name, data); + // store link to talk back when ready + pool[name].response = response; + // actual post + pool[name].socket.send(data); + pool[name].count++; + return true; + } + // failure + console.log('ws\tSEND\t[%s]\tfail to send (invalid connection)', name); + return false; + } + +};