Some ideas for improvement

About: Deezer:Download
25 mars modifié dans Discussions de script Chrome

It's funny, coz I started almost same work as K-mik@Z did to this moment. His version more readable, so I just link to my one.

click

Some things, I haven't seen in updated 1.0.5 (i edited 1.0 :( )
It may be interesting to embed in newer versions.

(showing size in bytes may help file by size among two almost identical. But wall of digits —
not best solution. So this function do conversion like this: 12345678 => "12 345 678")
function breakNumberByThreeDigit(num) {
    num=num.toString();
    let l = num.length;
    while ((l=l-3)>0)
        num=num.slice(0,l)+' '+num.slice(l);
    return num;
}



(in 'onmessage' handler. As localization cannot be determined in Worker, we export string as '^downloading 10 ^mb'
and line below replaces '^downloading' and '^mb' to lang['downloading'] and lang['mb'])
// to support multilang, we replace all '^word' to lang[word]
trackEl.querySelector('.status').innerHTML = state.replace(/\^(\w+)/g, (trash,key)=>lang.hasOwnProperty(key) ? lang[key] : trash);



// Open panel by pressing 'D'
addEventListener('keydown', e=>{
    if (e.code === 'KeyD')
        if (D.activeElement.nodeName !== 'INPUT')
            triggerEl.click();
    }
});



(deezer labs added hotkey support, so we may put here our own description)
// Add hotkey description to tooltip by 'H'-key
let iteration=0;
(function waitForHotkeysPanel() {
    if (iteration++<20) {
        if (document.querySelector('.hotkeys'))
            document.querySelector('.hotkeys .mapping').innerHTML += '<div class="hotkey"><div class="hotkey-icon single">D</div><div class="hotkey-label">'
            + lang['downloaderHotkey'] +'</div></div>'
        else
            setTimeout(waitForHotkeysPanel, 500)
    }
})();

Styles are rewritten too. Look at this and pick all you need ;)
Same with localized strings in russian (I'm native, so don't doubt in this :) (but not in englsh comments, huh))

Also I request choosing file name by parsing string like in AIMP.
e.g. I store files in format %TrackNumber. %Artist — %Title. dzPlayer share information about track number, but I cannot use it now because of hardcoded presets.

Best regards, AHOHNMYC

«1

Réponses

  • OK. I look at this. Thank you for your suggestions.
    I made a complete redesign of the code in module, and init them.
    I'm trying to integrate that for the next update.
    A little time will be necessary, I am not a pro of the JS, but I manage now ;)
  • 1 avril modifié Firefox
    I finished the few changes I had in progress plus rewrote the translation part on the idea of AHOHNMYC. I also integrated the keyboard shortcut D .
    The script now works for edge as well (though with a slight bug, slow for decrypt).

    Could you post a correction on the translation part (I changed some variables, see model English), so that I integrate it in the future update.

    en: { // Defaut Lng
    downloading: `Downloading`,
    decrypting: `Decrypting`,
    waiting: `Waiting`,
    standard: `standard`,
    choose: `Choose`,
    fileNaming: `file naming`, // translate[choose] & tranlate[choose + fileNaming]
    title: `Title`,
    artist: `Artist`,
    current: `Current track`,
    refresh: `Refresh the`, // translate[tracklist] & translate[refresh + tracklist]
    tracklist: `Track list`,
    clickToOpen: `Click to open\nor D key (keyboard shortcut)`,
    mb: `Мb`,
    downloaderHotkey: `Open "Deezer:Downloader" panel`,
    fixmeGM: `( ℹ ) Greasemonkey: bug, re-click on the link (once the conversion is complete).`
    },
    /* ------------------------------------------------------------- */



    // Part for Jonathan
    'pt-BR': {
    downloading: `Baixar`,
    decrypting: `Descriptografar`,
    waiting: `Carregando`,
    standard: `padrão`,
    choose: `Escolha`,
    fileNaming: `o nome do arquivo`,
    title: `Título`,
    artist: `Artista`,
    current: `Faixa atual`,
    refresh: `Atualize a`,
    tracklist: `Lista de faixas`,
    clickToOpen: `Clique para abrir\nou tecla D (atalho do teclado)`,
    mb: `Мb`,
    downloaderHotkey: `Abra o painel "Deezer: Downloader"`,
    fixmeGM: `( ℹ ) Greasemonkey: bug, clique novamente no link (quando a conversão estiver completa).`
    },


    // Part for AHOHNMYC
    ru: {
    downloading: `Загрузка`,
    decrypting: `Расшифровка`,
    waiting: `Ожидание загрузки`,
    standard: `стандартный`,
    choose: `Выбор`,
    fileNaming: `имени файла`,
    title: `Название`,
    artist: `Исполнитель`,
    current: `Текущий трек`,
    refresh: `обновить`,
    tracklist: `Список треков`,
    clickToOpen: `Клик для начала работы\nили ключ D (комбинация клавиш)`,
    mb: `МБ`,
    downloaderHotkey: `Открыть панель "Deezer:Downloader"`,
    fixmeGM: `( ℹ ) Greasemonkey: ошибка, повторно нажмите ссылку (после завершения преобразования).`
    }
    };

    // @name:en Deezer:D➲wnloader [Revived] - Download your music easily.
    // @description:en Download the currently playing song (or any song from the current tracklist) in any chosen format. Supports HQ even without Premium subscription.

    // @name:ru Deezer:D➲wnloader [Revived] - Загрузите свою музыку.
    // @description:ru Загрузите воспроизводимую в данный момент песню (или любую песню из текущего треклиста) в любом выбранном формате. Поддержка HQ даже без подписки на Premium.
  • 6 avril modifié Chrome

    Glad to see your attention about this script and my homble comment :smiley:

    // @name:ru Deezer:D➲wnloader [Revived] — Загрузите свою музыку.
    // @description:ru Загрузите воспроизводимую в данный момент песню (или любую песню из текущего треклиста) в любом выбранном формате. Поддержка HQ даже без подписки на Premium.
    
    // Part for AHOHNMYC
    ru: {
        downloading: `Загрузка`,
        decrypting: `Расшифровка`,
        waiting: `Ожидание загрузки`,
        standard: `стандартный`,
        choose: `Выбор`,
        fileNaming: `имени файла`,
        title: `Название`,
        artist: `Исполнитель`,
        current: `Текущий трек`,
        refresh: `обновить`,
        tracklist: `Список треков`,
        clickToOpen: `Клик для открытия панели\nили клавиша D`,
        mb: `МБ`,
        downloaderHotkey: `Открыть панель "Deezer:Downloader"`,
        fixmeGM: `(  ) Greasemonkey: ошибка, повторно нажмите ссылку (после завершения преобразования).`
    }
    

    That is.

    I only confused about Mb. Can't you change it to MB?
    Now it looks like files became 8 times smaller :smile:

  • AHOHNMYC, thanks for your help, it will help a lot!

    Just updated the script with part of your code!
  • 7 avril modifié Chrome

    There is trouble with typing D in Search field.
    Here have to be this check:

    if (D.activeElement.nodeName !== 'INPUT')
    

    I wrote similar code above ~

    Also, it's strange to watch only trigger on blank page, when interface is loading. Maybe do some displaying delay, as in working code below?

    // Wait displaying trigger element on blank page
    let delayStyleElement = D.head.appendChild(D.createElement('style'));
    delayStyleElement.textContent = '#dzdltrigger {display: none !important}';
    let waitForHeaderThenRemoveDelayStyle = ()=>{(!!document.querySelector('header')) ? delayStyleElement.remove() : setTimeout(waitForHeaderThenRemoveDelayStyle, 100) };
    waitForHeaderThenRemoveDelayStyle();
    
  • 8 avril modifié Vivaldi
    Sorry for the mistake and fixed in a new post (https://greasyfork.org/ru/forum/discussion/34067/x#Comment_49818) , thx for your return AHOHNMYC.
  • 9 avril modifié Chrome

    Oh, it's normal case with adopting other's code~

    There is another strange thing. Number three with tabulation sign does magic not ewerywhere, huh

    Maybe, temporary move \t\t\t to localization part? (Teh best solution there — popup element with <table>)

  • 9 avril modifié Vivaldi

    @AHOHNMYC a dit :
    Oh, it's normal case with adopting other's code~

    My English is not perfect, and I apologize if I hurt you, but by no means did I give you your job.
    I (corrected as soon as possible) simply copied the forget in the code.

    I simply tried to obfuscate the script with UglifyJS-online/ with as options (see in attached file)

    If you have proposals too, to avoid another inconvenience of this kind, I'm interested.
    (in the setting options.)

    There is another strange thing. Number three with tabulation sign does magic not ewerywhere, huh

    Maybe, temporary move \t\t\t to localization part? (Teh best solution there — popup element with <table>)

    I test that right now, and do not get angry if I write your proposal in the script.
    Teamwork.
    Basically, I do not code in JS. And I do my best.

    Into Vivaldi with ViolentMonkey I have this:

    Single \t work fine in Firefox but not in chrome based browser (chromium, vivaldi...), that explain why I chose \t\t\t

    PS: My inspiration source (JavaScript/Reference/Objets_globaux/String)

  • My English in most cases is a loan translation of Russian speech. So we are in equal position :smile: And yeah, Russian haven't articles at all, huh

    Oh yeah. Your code is nice-readable, and your best is really is.

    Above I mean separate element, like here:

    <div id="dzPopup">
        <table>
            <tr><td>Atrist:</td><td>Обе-Рек<td></tr>
            <tr><td>Title:</td><td>…<td></tr>
            …
        </table>
    </div>
    

    Now I'm workin on ID3 tags, and at same time occupied by work..
    Maybe you or @Jonathan%20Tavares create a GitHub repo?

  • Much better if @K-mik@Z create a GitHub repo, i'm just a noob here, i have a GitHub account, i made a script for mp3tag but that's all.

  • 9 avril modifié Vivaldi

    @AHOHNMYC a dit :
    Above I mean separate element, like here:
    html <div id="dzPopup"> <table> <tr><td>Atrist:</td><td>Обе-Рек<td></tr> <tr><td>Title:</td><td>…<td></tr> … </table> </div>

    Now I'm workin on ID3 tags, and at same time occupied by work..
    Maybe you or @Jonathan%20Tavares create a GitHub repo?

    OK, I look at that

  • @Jonathan Tavares, there is an update.
    Fixed debug output in Wokrer, now panel hides when user click on Search field
    https://paste.debian.net/plainh/556c25cd

  • 17 avril modifié Vivaldi

    @Jonathan Tavares I also did things. Could you wait until I integrate them into the @AHOHNMYC code. I'll post it to you as soon as you finish.
    reduction of the number of lines in the code (by rearrangement), reduction of the time loading of the code by async... Correction of the syntax (when we => parse <= ;) the code with jshint, no error message) ... Small things ...
    Works with SeaMonkey and 'GreaseMonkey Port' now.

    ======================================

    ==> New code with changes made by @AHOHNMYC

    Could you pass DEBUG = 1 to DEBUG = 0 please, I forgot.
    And the version too, THX changed

  • Speeding up code is perfect thing, but don't work as minifier, please. There are many online services for doing that for you. %%Or i'll start quote classics%%

    @K-mik@Z, what about passing isDEBUG value inside worker? I see old good hardcode ~

    isDEBUG = !0, Object.freeze(isDEBUG); // jshint ignore:line
    
  • 17 avril modifié Chrome

    Updated the code guys, btw, i loved the new description on the script:

    "Deezer:D➲wnloader [Revived] ... For that music can exceed the limits!"

    Awesome xD

  • 17 avril modifié Vivaldi

    @AHOHNMYC a dit :
    Speeding up code is perfect thing, but don't work as minifier, please. There are many online services for doing that for you. %%Or i'll start quote classics%%

    I do not understand. All I did was make with online tools.
    Except the MAP LANGUAGES SECTION.

    And I didn't speed to do that, I had done before you posted your code.

    When I saw it, I integrated your changes in it, that's all.
    What part of the code would you like me to unminify.

    @AHOHNMYC a dit :
    @K-mik@Z, what about passing isDEBUG value inside worker? I see old good hardcode ~

    isDEBUG = !0, Object.freeze(isDEBUG); // jshint ignore:line
    

    When I comment the line, the download blocks after 100% done.
    The code needs a log to work well, but I do not see which one.
    Why FREEZE var into worker (only).

    THX @Jonathan Tavares

    EDIT

    @K-mik@Z a dit :
    What part of the code would you like me to unminify.

    Perhaps for JS FLACMetadataEditor ? I suppose.
    When I parse it in JSHint with :
    /* jslint bitwise: true, esnext: true, moz: true, expr: true, sub:true, multistr: true */
    I have 42 warnings

    • 2 Missing '()' invoking a constructor.
    • 2 Missing semicolon.
    • 2 Missing semicolon.
    • 2 Missing semicolon.
    • 2 Missing semicolon.
    • 2 Missing '()' invoking a constructor.
    • 2 Missing semicolon.
    • 2 Missing '()' invoking a constructor.
    • 2 Missing semicolon.
    • 2 Missing '()' invoking a constructor.
    • 2 Missing semicolon.
    • 2 Missing semicolon.
    • 2 Missing semicolon.
    • 2 Missing semicolon.
    • 2 Missing semicolon.
    • 2 Missing semicolon.
    • 2 Missing semicolon.
    • 2 Missing semicolon.
    • 2 Missing semicolon.
    • 2 Missing semicolon.
    • 2 Missing semicolon.
    • 2 Missing semicolon.
    • 2 Missing semicolon.
    • 2 Missing '()' invoking a constructor.
    • 2 Missing semicolon.
    • 2 Missing semicolon.
    • 2 Missing semicolon.
    • 2 Missing semicolon.
    • 2 Missing '()' invoking a constructor.
    • 2 The body of a for in should be wrapped in an if statement to filter unwanted properties from the prototype.
    • 2 Missing semicolon.
    • 2 Missing semicolon.
    • 2 Missing semicolon.
    • 2 Missing semicolon.
    • 2 Missing semicolon.
    • 2 Missing semicolon.
    • 2 Missing '()' invoking a constructor.
    • 2 Missing '()' invoking a constructor.
    • 2 Missing semicolon.
    • 2 Missing '()' invoking a constructor.
    • 2 Missing semicolon.
    • 2 Missing semicolon.

    Then, I have use UglifyJS 3: Online JavaScript minifier.** If you would**, I can minify with UglifyJS 3 (it doesn't suppress ;) without changing** the layout of your coding** (is possible in the options).

  • 17 avril modifié Chrome

    Oh, if it's only for languages, without later plans to compress all code in one line, i'm calm :smile:

    Worker has own namespace, so there is no one isDEBUG at all untill we create it.
    I talk only about synchronization isDEBUG in Worker and isDEBUG used in other cases.
    Now it looks strange ~
    isDEBUG=0, but console has debug output.

    EDIT
    If it may help, of course do it.

  • Vivaldi

    isDEBUG=!0 => isDEBUG=1 => isDEBUG=true, I am wrong?

    @K-mik@Z a dit :
    When I comment the line, the download blocks after 100% done.

    console return isDEBUG is not defined.

    @AHOHNMYC a dit :
    isDEBUG=0, but console has debug output.

    And if isDEBUG=1, console has debug output too.
    I don't understand why??

  • 18 avril modifié Chrome

    isDEBUG=!0 => isDEBUG=1 => isDEBUG=true, I am wrong?

    In trifle. !0 === true, but !0 !== 1, but in common, of course, you are right.

    console return isDEBUG is not defined.

    Yes, and what are you waiting for?
    In this case isDEBUG is not defined in Worker scope

    I don't understand why??

    Honestly, i don't understand what you are don't understood ~
    In your opinion, it's normal if man trying to disable debug by setting isDEBUG=0, but watch in anyway?
    Or you are about misunderstanding Worker behaviour?

  • 18 avril modifié Vivaldi

    OK, I have supress all isDEBUG conditions on the worker isDEBUG = !0 ..., if (isDEBUG), and work fine. THX @AHOHNMYC for your explain.

    @K-mik@Z:
    I don't understand

    I'm learning JS with this Code. I am not a confirmed coder. That explains why

    Another point:

    The code was break in EDGE. Decrypt stop at 98%.
    Console return > TextDecoder is not defined.

    I tested with:

    let isFLAC = 'fLaC'; /*=== new TextDecoder().decode(data.subarray(0,4));*/
    

    And work.

    Is it good for you @AHOHNMYC ? If yes, I 've post a correction (with the modifications for isDEBUG too) that @Jonathan Tavares can post after confirmation.

    ==> Corrected code

    EDIT:

    I have work on a stylesheet (not mine) and apport some improvements, if you would
    Deezer:Darker

  • 18 avril modifié Chrome

    OK, learning with practice — best choice :smile:

    I tested with: ... And work.

    Yes. 'Coz isFLAC used only in resolution of MIME type for blob. I created it for future using, deezer may add OGG, or OPUS, for example. So now wrong isFLAC using can't break code flow.

    As is used as Boolean value, 'fLaC' => true. So, in fact variable's name don't reflect it's content.

    I haven't EDGE to test, but this replacement have to work correct.

    let decodeUTF8 = arr => Array.from(arr).map(n=>String.fromCharCode(n)).join('');
    let isMP3 = (data[0] === 0xFF && data[1] === 0xFB) || 'ID3' === decodeUTF8(data.subarray(0,3));
    let isFLAC = 'fLaC' === decodeUTF8(data.subarray(0,4));
    

    EDIT:

    So, i'm not completely got your position about console pollution from Worker. Now you just removed all isDEBUG, why?

    @AHOHNMYC написал:
    In your opinion, it's normal if man trying to disable debug by setting isDEBUG=0, but watch in anyway?

    EDIT2

    @K-mik@Z, deleting of .dltitle:nth-of-type(2){min-width:100%} — not by chance.
    That rule causes bottom scrollbar showing in Chrome.

  • 18 avril modifié Chrome

    @AHOHNMYC a dit :
    I haven't EDGE to test, but this replacement have to work correct.

    let decodeUTF8 = arr => Array.from(arr).map(n=>String.fromCharCode(n)).join('');
    let isMP3 = (data[0] === 0xFF && data[1] === 0xFB) || 'ID3' === decodeUTF8(data.subarray(0,3));
    let isFLAC = 'fLaC' === decodeUTF8(data.subarray(0,4));
    

    Ok, thx @AHOHNMYC ,

    ==> Here is the new corrected code tested in edge

  • @AHOHNMYC :

    EDIT2

    @K-mik@Z, deleting of .dltitle:nth-of-type(2){min-width:100%} — not by chance.
    That rule causes bottom scrollbar showing in Chrome.

    Ok, thx @AHOHNMYC ,

    ==> Here is the new corrected code

  • Updated. :)

  • 24 avril modifié Chrome

    I almost done complete rewriting. So, @K-mik@Z, @jonaaa20, please test this in all browsers and script managers you have ~

    code

    It's only for testing purposes (e.g. @K-mik@Z, i doubt that Edge can correctly handle FLAC tags adding).
    Some things not implemented (e.g. azLyrics parser) and not rewritten to this moment, but almost everything written stay in this state in final.

    Name format:
    default: '%NN. %Artist - %Title %Version'
    result:  '13. System of a Down - Ego Brain (Album Version)' (for example)
    
    Every '%tag' will be replaced to real 'tag' value.
    
    Name may consist of these tags:
    
    Common: 'artist', 'album', 'disk', 'time', 'title', 'version', 'NN' (track number)
    
    Deezer-specific:
    'cover' - cover id
    'gain'  - sort of. Looks like Peak normalization
    'id'    - track id
    
    Case of tag\'s impact to resulting case:
    '%ARTIST' => 'SYSTEM OF A DOWN'
    '%Artist' => 'System of a Down'
    '%artist' => 'system of a down'
    
    If count of digits in track number less than `N` count, it will be padded with zeroes:
    If track number is 2:
    '%N'    => 2
    '%NN'   => 02
    '%NNN'  => 002
    '%NNNN' => 0002
    
    If track number is 42:
    '%N'    => 42
    '%NN'   => 42
    '%NNN'  => 042
    '%NNNN' => 0042
    
    If you don\'t want to replace '%tag' with real value, you have to escape '%' like this '\%tag'
    
  • 24 avril modifié Chrome

    Okay i did some tests, there's a little bug (maybe a bug), how can i explain it... well...

    I attached a screenshot and a gif, when i click on the same song on "track list" area on the script, it shows that is downloading from the "now playing" area, got it? a bit hard to explain but hope that you understand :D

    I'm doing some stress test, no issues so far.

  • 24 avril modifié Chrome

    Oh, dat is. I understand. In my opinion, "Current track" area is not needed, because current track highlighted with gray among others.
    Of course, i can do some crunches, but code became less readable ~

    Are you need the "Current track" area?

  • Android WebView
    "Current track" area is useless in my opinion, we just need the "Track list". You can delete it from the code if you want, I personally never used it.
  • I never used it too. So, i'll remove this one.

  • I made complete rewrite. Now code became more readable, name editing improved, UI mimicry increased.
    Added azLyrics parser, so now if lyrics exists it will be embedded into file.

    Fixed working on firefox+greasemonkey.
    Tested on firefox+(tamper, violent, greasy), chromium+tamper.

    https://paste.debian.net/plainh/04bc0830

    Also, i think that notes about file name editing have to be on main page. Or at least, link to comment.

Connectez-vous ou Inscrivez-vous pour répondre.