├── .gitignore ├── LICENSE ├── README.md ├── cookie.go ├── download.go ├── go.mod ├── go.sum ├── handler.go ├── main.go ├── makefile ├── parser.go └── token.go /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | build.sh 3 | release/ 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Bahamut Anime Downloader 2 | 3 | 4 | ## Important 5 | This tool is no longer maintained. 6 | 7 | --- 8 | 9 | Download anime from [動畫瘋](https://ani.gamer.com.tw/) 10 | 11 | ## Installation 12 | This program uses ffmpeg to merge the chunk file and output the video with the original codecs. 13 | 14 | Therefore, ffmpeg need to be available in `PATH` or same directory. 15 | 16 | ## Compilation 17 | Using Makefile 18 | ``` 19 | git clone https://github.com/c0re100/BahamutAnimeDownloader.git 20 | cd BahamutAnimeDownloader 21 | make deps # Install the dependences 22 | make 23 | ``` 24 | Or Manual compile 25 | ``` 26 | git clone https://github.com/c0re100/BahamutAnimeDownloader.git 27 | cd BahamutAnimeDownloader 28 | go build 29 | 30 | # You need to make sure the dependences have been installed 31 | ``` 32 | 33 | ## Usage 34 | For example, you want to download [驚爆危機 Invisible Victory 第12集](https://ani.gamer.com.tw/animeVideo.php?sn=10434) 35 | 36 | Open the downloader and type the sn id (animeVideo.php?sn=`10434`) 37 | 38 | Then you can downloading the videos as fast as possible (Depending on your network). 39 | 40 | ![example](https://i.imgur.com/BpuQckG.png) 41 | 42 | ## Command line arguments 43 | 44 | ### Select sn 45 | 46 | `AniDownloader -s 10434` 47 | 48 | ### Video Quality Option 49 | You can start a program with command line argument to select quality, otherwise the default quality is 720p. 50 | 51 | Quality 52 | * 360p 53 | * 540p 54 | * 720p 55 | * 1080p # Only for bahamut premium member, and needed to be provided Cookies file 56 | 57 | `AniDownloader -quality="720p"` or `Anidownloader -q 720p` 58 | 59 | ### Cookies 60 | If you are the *premium member* and want to download 1080p video 61 | 62 | Using -c option to provide your Cookies file 63 | 64 | `AniDownloader -c cookies.txt -q 1080p` 65 | 66 | Cookies file can be Raw cookie format or Nestscape cookie format 67 | ``` 68 | 1. Raw cookies: 69 | 70 | name = value; name = value; ... 71 | 72 | 2. Nestscape format: 73 | 74 | # Netscape HTTP Cookie File 75 | 76 | .example.org TRUE / FALSE 1552060831 remember_me true 77 | .example.org TRUE / FALSE 1552060831 APISID DijdSAOAjgwijnhFMndsjiejfdSDNSgfsikasASIfgijsowITITeoknsd 78 | .example.org TRUE / FALSE 1552060831 static_files iy1aBf1JhQR 79 | 80 | ``` 81 | 82 | Then example of watching 1080p video with Cookies 83 | 84 | ![example](https://i.imgur.com/aoVMUVP.png) 85 | 86 | ### Output 87 | 88 | Using -o option to set output path 89 | 90 | `AniDownloader -s 10434 -q 720p -o .\Anime` -------------------------------------------------------------------------------- /cookie.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "io/ioutil" 7 | "net/http" 8 | "os" 9 | "strings" 10 | 11 | "github.com/MercuryEngineering/CookieMonster" 12 | ) 13 | 14 | func (h *bahamut) readCookieFile() { 15 | if h.cookie != "" { 16 | _, err := os.Stat(h.cookie) 17 | isErr("Cookie file error -", err) 18 | 19 | cookies, err := cookiemonster.ParseFile(h.cookie) 20 | isErr("Parsing Cookie file failed -", err) 21 | 22 | if len(cookies) != 0 { 23 | for _, ck := range cookies { 24 | h.rawCookie += ck.Name + "=" + ck.Value + "; " 25 | } 26 | } else { 27 | data, err := ioutil.ReadFile(h.cookie) 28 | isErr("Read cookie file failed -", err) 29 | h.rawCookie = string(data) 30 | h.rawCookie = strings.TrimRight(h.rawCookie, "\n\r") 31 | } 32 | } 33 | } 34 | 35 | func (h *bahamut) refreshCookie() { 36 | if h.rawCookie != "" { 37 | req, err := http.NewRequest("GET", "https://ani.gamer.com.tw/", nil) 38 | isErr("Create request failed - ", err) 39 | 40 | req.Header.Add("cookie", h.rawCookie) 41 | req.Header.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36") 42 | req.Header.Add("referer", "https://ani.gamer.com.tw/") 43 | resp, err := http.DefaultClient.Do(req) 44 | isErr("Refresh Cookie failed -", err) 45 | 46 | for _, ck := range resp.Cookies() { 47 | if ck.Value == "deleted" { 48 | isErr("Set Cookie failed -", errors.New("Seems your cookie is expired.")) 49 | } else { 50 | h.setCookie(ck.Name, ck.Value) 51 | } 52 | } 53 | 54 | if len(resp.Cookies()) > 0 { 55 | ioutil.WriteFile(h.cookie, []byte(h.rawCookie), 0755) 56 | fmt.Println("Cookie refreshed.") 57 | } else { 58 | fmt.Println("No need refresh cookie.") 59 | } 60 | } 61 | } 62 | 63 | func (h *bahamut) setCookie(name, value string) { 64 | header := http.Header{} 65 | header.Add("Cookie", h.rawCookie) 66 | request := http.Request{Header: header} 67 | 68 | // clear current cookie first 69 | h.rawCookie = "" 70 | 71 | for _, f := range request.Cookies() { 72 | if f.Name == name { 73 | f.Value = value 74 | } 75 | h.rawCookie += f.Name + "=" + f.Value + "; " 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /download.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "fmt" 7 | "io" 8 | "io/ioutil" 9 | "net/http" 10 | "os" 11 | "path" 12 | "path/filepath" 13 | "strings" 14 | "time" 15 | 16 | "github.com/korovkin/limiter" 17 | "gopkg.in/cheggaaa/pb.v1" 18 | ) 19 | 20 | func (h *bahamut) getM3U8() { 21 | req, err := http.NewRequest("GET", "https://ani.gamer.com.tw/ajax/m3u8.php?sn="+h.sn+"&device="+h.deviceId, nil) 22 | isErr("Create request failed - ", err) 23 | 24 | req.Header.Add("cookie", h.rawCookie) 25 | req.Header.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36") 26 | req.Header.Add("referer", "https://ani.gamer.com.tw/animeVideo.php?sn="+h.sn) 27 | req.Header.Add("origin", "https://ani.gamer.com.tw") 28 | resp, err := http.DefaultClient.Do(req) 29 | isErr("Get m3u8 playlist failed -", err) 30 | 31 | defer resp.Body.Close() 32 | body, err := ioutil.ReadAll(resp.Body) 33 | isErr("Read response failed -", err) 34 | 35 | var bahaData map[string]interface{} 36 | err = json.Unmarshal(body, &bahaData) 37 | isErr("Parse json failed -", err) 38 | 39 | if bahaData["src"].(string) != "" { 40 | h.mUrl = bahaData["src"].(string) 41 | } else { 42 | isErr("Please try again -", errors.New("src not found")) 43 | } 44 | } 45 | 46 | func (h *bahamut) downloadM3U8() { 47 | // Create a temporary directory for storing 48 | if h.outputPath == "output" { 49 | h.tmp = "tmp" + h.sn 50 | } else { 51 | h.tmp = filepath.Join(h.outputPath, "tmp" + h.sn) 52 | } 53 | os.MkdirAll(h.tmp, 0755) 54 | 55 | var choice string 56 | h.plName, choice = h.getQuality() 57 | fmt.Println("Your choice:", choice) 58 | 59 | out, err := os.Create(filepath.Join(h.tmp, h.plName)) 60 | isErr("Create m3u8 playlist failed -", err) 61 | 62 | defer out.Close() 63 | resp := h.request("downloadM3U8", strings.Replace(h.mUrl, "playlist.m3u8", h.plName, -1)) 64 | 65 | defer resp.Body.Close() 66 | _, err = io.Copy(out, resp.Body) 67 | isErr("m3u8 playlist save failed -", err) 68 | 69 | fmt.Println("m3u8 playlist downloaded.") 70 | } 71 | 72 | func (h *bahamut) downloadKey(keyUrl string) string { 73 | filename := strings.Split(path.Base(keyUrl), "?")[0] 74 | 75 | out, err := os.Create(filepath.Join(h.tmp, filename)) 76 | isErr("Create key file failed -", err) 77 | 78 | defer out.Close() 79 | resp := h.request("downloadKey", keyUrl) 80 | 81 | defer resp.Body.Close() 82 | _, err = io.Copy(out, resp.Body) 83 | isErr("Key file save failed -", err) 84 | fmt.Println("m3u8 key file downloaded.") 85 | 86 | return strings.Split(path.Base(keyUrl), "?")[0] 87 | } 88 | 89 | func (h *bahamut) downloadChunk(chuckUrl string) bool { 90 | filename := strings.Split(path.Base(chuckUrl), "?")[0] 91 | 92 | // Check chunk exist or not 93 | fi, err := os.Stat(filepath.Join(h.tmp, filename)) 94 | if err == nil && fi.Size() != 0 { 95 | return true 96 | } 97 | 98 | // Create a chunk file 99 | out, err := os.Create(filepath.Join(h.tmp, filename)) 100 | isErr("Create "+filename+" failed -", err) 101 | 102 | req, err := http.NewRequest("GET", chuckUrl, nil) 103 | isErr("Create request failed - ", err) 104 | 105 | req.Header.Add("cookie", h.rawCookie) 106 | req.Header.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36") 107 | req.Header.Add("referer", "https://ani.gamer.com.tw/animeVideo.php?sn="+h.sn) 108 | req.Header.Add("origin", "https://ani.gamer.com.tw") 109 | 110 | resp, err := http.DefaultClient.Do(req) 111 | if err != nil { 112 | fmt.Println("Download "+filename+" file failed -", err) 113 | fmt.Println("Retrying -", filename) 114 | out.Close() 115 | os.Remove(filepath.Join(h.tmp, filename)) 116 | time.Sleep(500 * time.Millisecond) 117 | return false 118 | } 119 | 120 | _, err = io.Copy(out, resp.Body) 121 | if err != nil { 122 | fmt.Println(filename+" save failed -", err) 123 | fmt.Println("Retrying -", filename) 124 | out.Close() 125 | os.Remove(filepath.Join(h.tmp, filename)) 126 | time.Sleep(500 * time.Millisecond) 127 | return false 128 | } 129 | out.Close() 130 | return true 131 | } 132 | 133 | func (h *bahamut) start() { 134 | h.bar = pb.StartNew(len(h.chuckList)) 135 | limit := limiter.NewConcurrencyLimiter(64) 136 | 137 | for _, url := range h.chuckList { 138 | part := url 139 | limit.Execute(func() { 140 | for { 141 | if h.downloadChunk(part) { 142 | h.bar.Increment() 143 | break 144 | } 145 | } 146 | }) 147 | } 148 | limit.Wait() 149 | 150 | h.bar.Finish() 151 | } 152 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/c0re100/bahamutanimedownloader 2 | 3 | go 1.16 4 | 5 | require ( 6 | github.com/MercuryEngineering/CookieMonster v0.0.0-20180304172713-1584578b3403 7 | github.com/grafov/m3u8 v0.11.1 8 | github.com/korovkin/limiter v0.0.0-20190919045942-dac5a6b2a536 9 | github.com/mattn/go-runewidth v0.0.12 // indirect 10 | golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57 // indirect 11 | gopkg.in/cheggaaa/pb.v1 v1.0.28 12 | ) 13 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/MercuryEngineering/CookieMonster v0.0.0-20180304172713-1584578b3403 h1:EtZwYyLbkEcIt+B//6sujwRCnHuTEK3qiSypAX5aJeM= 2 | github.com/MercuryEngineering/CookieMonster v0.0.0-20180304172713-1584578b3403/go.mod h1:mM6WvakkX2m+NgMiPCfFFjwfH4KzENC07zeGEqq9U7s= 3 | github.com/grafov/m3u8 v0.11.1 h1:igZ7EBIB2IAsPPazKwRKdbhxcoBKO3lO1UY57PZDeNA= 4 | github.com/grafov/m3u8 v0.11.1/go.mod h1:nqzOkfBiZJENr52zTVd/Dcl03yzphIMbJqkXGu+u080= 5 | github.com/korovkin/limiter v0.0.0-20190919045942-dac5a6b2a536 h1:QwKnpk6xFW80HVFKqiIHTzK19UF62mRWejcUr/q6z4I= 6 | github.com/korovkin/limiter v0.0.0-20190919045942-dac5a6b2a536/go.mod h1:bttpekv26JrhFNCYlxnxn8a1jw8Q0gi8iHe0RC4JLBg= 7 | github.com/mattn/go-runewidth v0.0.12 h1:Y41i/hVW3Pgwr8gV+J23B9YEY0zxjptBuCWEaxmAOow= 8 | github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= 9 | github.com/rivo/uniseg v0.1.0 h1:+2KBaVoUmb9XzDsrx/Ct0W/EYOSFf/nWTauy++DprtY= 10 | github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= 11 | golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57 h1:F5Gozwx4I1xtr/sr/8CFbb57iKi3297KFs0QDbGN60A= 12 | golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 13 | gopkg.in/cheggaaa/pb.v1 v1.0.28 h1:n1tBJnnK2r7g9OW2btFH91V92STTUevLXYFb8gy9EMk= 14 | gopkg.in/cheggaaa/pb.v1 v1.0.28/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= 15 | -------------------------------------------------------------------------------- /handler.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "log" 7 | "net/http" 8 | "os" 9 | "os/exec" 10 | "path/filepath" 11 | "strings" 12 | "time" 13 | ) 14 | 15 | func envCheck() { 16 | dir, err := filepath.Abs(filepath.Dir(os.Args[0])) 17 | isErr("Path not found", err) 18 | os.Setenv("PATH", os.Getenv("PATH")+";"+dir) 19 | 20 | err = exec.Command("ffmpeg").Run() 21 | if err != nil { 22 | if strings.Contains(err.Error(), "executable file not found") { 23 | isErr("ffmpeg not found -", errors.New("please download from official website first")) 24 | } 25 | } 26 | } 27 | 28 | func isErr(msg string, err error) { 29 | if err != nil { 30 | f, e := os.OpenFile("error.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0755) 31 | if e != nil { 32 | log.Fatal(err.Error()) 33 | } 34 | 35 | log.SetOutput(f) 36 | msg := msg + " " + err.Error() 37 | fmt.Println(msg) 38 | log.Fatal(msg) 39 | } 40 | } 41 | 42 | func (h *bahamut) getQuality() (string, string) { 43 | return h.res, h.quality 44 | } 45 | 46 | func (h *bahamut) request(action, url string) *http.Response { 47 | req, err := http.NewRequest("GET", url, nil) 48 | if err != nil { 49 | isErr("Create "+action+" request failed - ", err) 50 | } 51 | 52 | req.Header.Add("cookie", h.rawCookie) 53 | req.Header.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36") 54 | req.Header.Add("referer", "https://ani.gamer.com.tw/animeVideo.php?sn="+h.sn) 55 | req.Header.Add("origin", "https://ani.gamer.com.tw") 56 | resp, err := http.DefaultClient.Do(req) 57 | if err != nil { 58 | isErr("Create "+action+" request failed - ", err) 59 | } 60 | 61 | return resp 62 | } 63 | 64 | func (h *bahamut) mergeChunk() { 65 | fmt.Println("Merging chunk file...please wait a moment...") 66 | os.Mkdir(h.outputPath, 0755) 67 | outputPath := filepath.Join(h.outputPath, h.sn+".mp4") 68 | exec.Command("ffmpeg", "-allowed_extensions", "ALL", "-y", "-i", h.tmp+"/"+h.plName, "-c", "copy", outputPath).Run() 69 | fmt.Println("File location: " + outputPath) 70 | } 71 | 72 | func (h *bahamut) cleanUp() { 73 | // Delete a temporary directory 74 | os.RemoveAll(h.tmp) 75 | 76 | fmt.Println("Cleaned up.") 77 | fmt.Printf("Total time: %ds", time.Now().Unix()-h.startTime) 78 | } 79 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "strconv" 6 | "time" 7 | 8 | "gopkg.in/cheggaaa/pb.v1" 9 | ) 10 | 11 | type bahamut struct { 12 | sn string 13 | mUrl string 14 | plName string 15 | chuckList []string 16 | bar *pb.ProgressBar 17 | startTime int64 18 | deviceId string 19 | cookie string 20 | rawCookie string 21 | quality string 22 | res string 23 | tmp string 24 | isPremium bool 25 | time string 26 | outputPath string 27 | } 28 | 29 | func main() { 30 | envCheck() 31 | 32 | handler := &bahamut{ 33 | startTime: time.Now().Unix(), 34 | } 35 | 36 | flag.StringVar(&handler.sn, "sn", "", "set sn") 37 | flag.StringVar(&handler.sn, "s", "", "set sn(shorthand)") 38 | flag.StringVar(&handler.cookie, "cookie", "", "cookie") // raw cookie 39 | flag.StringVar(&handler.cookie, "c", "", "cookie(shorthand)") 40 | flag.StringVar(&handler.time, "t", "30", "time(shorthand)") 41 | flag.StringVar(&handler.quality, "quality", "720p", "set resolution") 42 | flag.StringVar(&handler.quality, "q", "720p", "set resolution(shorthand)") 43 | flag.StringVar(&handler.outputPath, "o", "output", "Output Path(shorthand)") 44 | flag.Parse() 45 | 46 | handler.askForSN() 47 | handler.readCookieFile() 48 | handler.refreshCookie() 49 | handler.getDeviceId() 50 | handler.gainAccess() 51 | handler.checkPremium() 52 | handler.unlock() 53 | handler.checkLock() 54 | handler.unlock() 55 | handler.unlock() 56 | if !handler.isPremium { 57 | handler.startAd() 58 | t, err := strconv.Atoi(handler.time) 59 | isErr("convert the time to integer failed - ", err) 60 | time.Sleep(time.Duration(t) * time.Second) 61 | handler.skipAd() 62 | } 63 | handler.videoStart() 64 | handler.checkNoAd() 65 | handler.getM3U8() 66 | handler.parseMasterList() 67 | handler.downloadM3U8() 68 | handler.parseM3U8() 69 | handler.start() 70 | handler.mergeChunk() 71 | handler.cleanUp() 72 | } 73 | -------------------------------------------------------------------------------- /makefile: -------------------------------------------------------------------------------- 1 | GOCMD=go 2 | GOBUILD=$(GOCMD) build 3 | GOCLEAN=$(GOCMD) clean 4 | GOGET=$(GOCMD) get 5 | BINARY_NAME=AniDownloader 6 | 7 | all: build 8 | build: 9 | $(GOBUILD) -o $(BINARY_NAME) -v 10 | clean: 11 | $(GOCLEAN) 12 | rm -f $(BINARY_NAME) 13 | run: 14 | $(GOBUILD) -o $(BINARY_NAME) -v ./... 15 | ./$(BINARY_NAME) 16 | deps: 17 | $(GOGET) github.com/grafov/m3u8 18 | $(GOGET) github.com/korovkin/limiter 19 | $(GOGET) github.com/MercuryEngineering/CookieMonster 20 | $(GOGET) gopkg.in/cheggaaa/pb.v1 21 | -------------------------------------------------------------------------------- /parser.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "errors" 6 | "fmt" 7 | "io/ioutil" 8 | "net/http" 9 | "net/url" 10 | "os" 11 | "path" 12 | "path/filepath" 13 | "strconv" 14 | "strings" 15 | 16 | "github.com/grafov/m3u8" 17 | ) 18 | 19 | func (h *bahamut) askForSN() { 20 | var sn string 21 | 22 | sn = h.sn 23 | for sn == "" { 24 | fmt.Println("Please type anime sn id: ") 25 | fmt.Scanln(&sn) 26 | } 27 | 28 | // extract URL input 29 | _, err := strconv.Atoi(sn) 30 | if err != nil { 31 | if strings.Contains(sn, "animeVideo") { 32 | u, err := url.Parse(sn) 33 | isErr("Extract url failed -", err) 34 | 35 | qStr, err := url.ParseQuery(u.RawQuery) 36 | isErr("Parse query string failed -", err) 37 | if qStr.Get("sn") == "" { 38 | isErr("Extract sn id failed -", errors.New("sn id not found")) 39 | } 40 | sn = qStr.Get("sn") 41 | } else { 42 | isErr("Please try again -", errors.New("format not corret, Allow: numeric / URL")) 43 | } 44 | } 45 | 46 | h.sn = sn 47 | } 48 | 49 | func (h *bahamut) parseMasterList() { 50 | req, err := http.NewRequest("GET", h.mUrl, nil) 51 | isErr("Create request failed - ", err) 52 | 53 | req.Header.Add("cookie", h.rawCookie) 54 | req.Header.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36") 55 | req.Header.Add("referer", "https://ani.gamer.com.tw/animeVideo.php?sn="+h.sn) 56 | req.Header.Add("origin", "https://ani.gamer.com.tw") 57 | resp, err := http.DefaultClient.Do(req) 58 | isErr("Get m3u8 playlist failed -", err) 59 | 60 | defer resp.Body.Close() 61 | p, listType, err := m3u8.DecodeFrom(bufio.NewReader(resp.Body), true) 62 | isErr("Parse m3u8 playlist failed -", err) 63 | 64 | switch listType { 65 | case m3u8.MASTER: 66 | masterpl := p.(*m3u8.MasterPlaylist) 67 | var res_list []string 68 | for _, list := range masterpl.Variants { 69 | res := strings.Split(list.Resolution, "x")[1] 70 | res_list = append(res_list, res+"p") 71 | if h.quality == res + "p" { 72 | h.res = strings.Split(list.URI, "?")[0] 73 | } 74 | 75 | } 76 | 77 | if h.res == "" { 78 | fmt.Println("Not supported resolution in this video: " + h.quality) 79 | fmt.Println("Only support these resolution: ") 80 | fmt.Println(res_list) 81 | os.Exit(1) 82 | } 83 | } 84 | fmt.Println("Get m3u8 playlist.") 85 | } 86 | 87 | func (h *bahamut) parseM3U8() { 88 | f, err := os.Open(filepath.Join(h.tmp, h.plName)) 89 | isErr("Failed to read m3u8 playlist -", err) 90 | 91 | pl, listType, err := m3u8.DecodeFrom(bufio.NewReader(f), true) 92 | isErr("Parse m3u8 playlist failed -", err) 93 | 94 | switch listType { 95 | case m3u8.MEDIA: 96 | mediapl := pl.(*m3u8.MediaPlaylist) 97 | newPl, e := m3u8.NewMediaPlaylist(mediapl.WinSize(), mediapl.Count()) 98 | isErr("Creating new m3u8 playlist failed - ", e) 99 | 100 | prefix := strings.Split(h.mUrl, "playlist.m3u8")[0] 101 | newPl.SetDefaultKey(mediapl.Key.Method, h.downloadKey(mediapl.Key.URI), "", "", "") 102 | for _, chuck := range mediapl.Segments { 103 | if chuck != nil { 104 | h.chuckList = append(h.chuckList, prefix+chuck.URI) 105 | newPl.Append(strings.Split(path.Base(chuck.URI), "?")[0], chuck.Duration, "") 106 | } 107 | } 108 | newPl.Close() 109 | 110 | ioutil.WriteFile(filepath.Join(h.tmp, h.plName), newPl.Encode().Bytes(), 0755) 111 | fmt.Println("All segments parsed! Download is starting...") 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /token.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "fmt" 7 | "io/ioutil" 8 | "math/rand" 9 | "net/http" 10 | "time" 11 | ) 12 | 13 | func randomString(num int) string { 14 | rand.Seed(time.Now().UTC().UnixNano()) 15 | const chars = "abcdefghijklmnopqrstuvwxyz0123456789" 16 | result := make([]byte, num) 17 | for i := 0; i < num; i++ { 18 | result[i] = chars[rand.Intn(len(chars))] 19 | } 20 | return string(result) 21 | } 22 | 23 | func (h *bahamut) getDeviceId() { 24 | req, err := http.NewRequest("GET", "https://ani.gamer.com.tw/ajax/getdeviceid.php?id="+h.deviceId, nil) 25 | isErr("Create request failed - ", err) 26 | 27 | if h.cookie != "" { 28 | req.Header.Add("cookie", h.rawCookie) 29 | } 30 | 31 | req.Header.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36") 32 | req.Header.Add("referer", "https://ani.gamer.com.tw/animeVideo.php?sn="+h.sn) 33 | req.Header.Add("origin", "https://ani.gamer.com.tw") 34 | resp, err := http.DefaultClient.Do(req) 35 | isErr("Get Device ID failed -", err) 36 | 37 | defer resp.Body.Close() 38 | body, err := ioutil.ReadAll(resp.Body) 39 | isErr("Read response failed -", err) 40 | 41 | var bahaData map[string]interface{} 42 | err = json.Unmarshal(body, &bahaData) 43 | isErr("Parse json failed -", err) 44 | 45 | h.deviceId = bahaData["deviceid"].(string) 46 | 47 | for _, ck := range resp.Cookies() { 48 | if ck.Name == "nologinuser" { 49 | h.rawCookie = "nologinuser=" + ck.Value 50 | } 51 | } 52 | } 53 | 54 | func (h *bahamut) gainAccess() { 55 | resp := h.request("gainAccess", "https://ani.gamer.com.tw/ajax/token.php?adID=0&sn="+h.sn+"&device="+h.deviceId+"&hash="+randomString(12)) 56 | 57 | defer resp.Body.Close() 58 | body, err := ioutil.ReadAll(resp.Body) 59 | isErr("Read response failed -", err) 60 | 61 | var bahaData map[string]interface{} 62 | err = json.Unmarshal(body, &bahaData) 63 | isErr("Parse json failed -", err) 64 | 65 | if bahaData["error"] != nil { 66 | isErr("Something happened -", errors.New("Where are you from? ")) 67 | } else { 68 | fmt.Println("Gained access.") 69 | } 70 | } 71 | 72 | func (h *bahamut) checkPremium() { 73 | resp := h.request("checkPremium", "https://ani.gamer.com.tw/ajax/token.php?sn="+h.sn+"&device="+h.deviceId+"&hash="+randomString(12)) 74 | 75 | defer resp.Body.Close() 76 | body, err := ioutil.ReadAll(resp.Body) 77 | isErr("Read response failed -", err) 78 | 79 | var bahaData map[string]interface{} 80 | err = json.Unmarshal(body, &bahaData) 81 | isErr("Parse json failed -", err) 82 | 83 | if bahaData["vip"] != nil && bahaData["vip"].(bool) == true { 84 | h.isPremium = true 85 | fmt.Println("You're Premium user") 86 | } else { 87 | h.isPremium = false 88 | fmt.Println("You're not Premium user") 89 | } 90 | } 91 | 92 | func (h *bahamut) checkNoAd() { 93 | resp := h.request("checkNoAd", "https://ani.gamer.com.tw/ajax/token.php?sn="+h.sn+"&device="+h.deviceId+"&hash="+randomString(12)) 94 | 95 | defer resp.Body.Close() 96 | body, err := ioutil.ReadAll(resp.Body) 97 | isErr("Read response failed -", err) 98 | 99 | var bahaData map[string]interface{} 100 | err = json.Unmarshal(body, &bahaData) 101 | isErr("Parse json failed -", err) 102 | 103 | if bahaData["time"] != nil { 104 | if bahaData["time"].(float64) == 1 { 105 | fmt.Println("Adaway.") 106 | } else { 107 | isErr("Something happened -", errors.New("Ads not away? ")) 108 | } 109 | } else { 110 | isErr("Something happened -", errors.New("Where are you from? ")) 111 | } 112 | } 113 | 114 | func (h *bahamut) startAd() { 115 | h.request("startAd", "https://ani.gamer.com.tw/ajax/videoCastcishu.php?sn="+h.sn+"&s=194699").Body.Close() 116 | } 117 | 118 | func (h *bahamut) skipAd() { 119 | h.request("skipAd", "https://ani.gamer.com.tw/ajax/videoCastcishu.php?sn="+h.sn+"&s=194699&ad=end").Body.Close() 120 | } 121 | 122 | func (h *bahamut) unlock() { 123 | h.request("unlock", "https://ani.gamer.com.tw/ajax/unlock.php?sn="+h.sn+"&ttl=0").Body.Close() 124 | } 125 | 126 | func (h *bahamut) checkLock() { 127 | h.request("checkLock", "https://ani.gamer.com.tw/ajax/checklock.php?device="+h.deviceId+"sn="+h.sn).Body.Close() 128 | } 129 | 130 | func (h *bahamut) videoStart() { 131 | h.request("videoStart", "https://ani.gamer.com.tw/ajax/videoStart.php?sn="+h.sn).Body.Close() 132 | } 133 | --------------------------------------------------------------------------------