├── .dockerignore ├── .env.sample ├── .github └── workflows │ └── main.yml ├── .gitignore ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── assets └── index ├── cmd └── main.go ├── config └── profiles.json ├── dataservice ├── asset.go ├── asset_test.go ├── dataservice.go ├── dataservice_test.go ├── mean_size_ratio.go ├── mocks │ ├── AssetDatabase.go │ ├── ClientHelper.go │ ├── CollectionHelper.go │ ├── DatabaseHelper.go │ ├── MeanSizeRatioDatabase.go │ ├── SingleResultHelper.go │ ├── SizeRatioDatabase.go │ ├── StorageDealDatabase.go │ ├── TranscodingDealDatabase.go │ ├── UploadDatabase.go │ └── UserDatabase.go ├── size_ratio.go ├── storage_deal.go ├── transcoding_deal.go ├── upload.go └── user.go ├── go.mod ├── go.sum ├── internal └── internal.go ├── livepeerPull ├── configs │ └── profiles.json ├── darwin │ └── place_mac_livepeer_bin_here └── linux │ └── place_linux_livepeer_bin_here ├── model └── model.go ├── server ├── routes │ ├── asset.go │ ├── pricing.go │ ├── pricing_test.go │ ├── upload.go │ └── upload_test.go └── server.go └── util ├── files.go ├── livepeer.go ├── multipart_uploader.go ├── pinata.go ├── poller.go ├── pow.go ├── scripts.go └── segment.go /.dockerignore: -------------------------------------------------------------------------------- 1 | .git 2 | # Binaries for programs and plugins 3 | *.exe 4 | *.exe~ 5 | *.dll 6 | *.so 7 | *.dylib 8 | 9 | # Test binary, built with `go test -c` 10 | *.test 11 | 12 | # Output of the go coverage tool, specifically when used with LiteIDE 13 | *.out 14 | 15 | # Dependency directories (remove the comment below to include it) 16 | # vendor/ 17 | 18 | # Misc. 19 | .DS_Store 20 | *.sqlite3 21 | assets/* 22 | !assets/index 23 | .vscode/ 24 | .idea/ 25 | main 26 | .env 27 | -------------------------------------------------------------------------------- /.env.sample: -------------------------------------------------------------------------------- 1 | LIVEPEER_COM_API_KEY=mylivepeerapikey 2 | LIVEPEER_PRICING_TOOL=https://livepeer-pricing-tool.com 3 | POWERGATE_ADDR=127.0.0.1:5002 4 | IPFS_REV_PROXY_ADDR=127.0.0.1:6002 5 | TRUSTED_MINERS="m1 m2 m3" 6 | POLL_INTERVAL=30 7 | PORT=8000 8 | PINATA_API_KEY=mypinataapikey 9 | PINATA_SECRET_KEY=mypinatasecretkey 10 | IPFS_GATEWAY=https://demuxipfsrevproxy.onrender.com/ipfs/ 11 | POW_TOKEN=mypowtoken 12 | DEMUX_URL=http://localhost:8000/ 13 | MONGO_URI=mongodb://127.0.0.1:27017/demux 14 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | on: [push, pull_request] 2 | name: Tests 3 | jobs: 4 | build: 5 | strategy: 6 | matrix: 7 | go-version: [1.15.2] 8 | os: [ubuntu-latest, macos-latest] 9 | runs-on: ${{ matrix.os }} 10 | steps: 11 | - name: Checkout 12 | uses: actions/checkout@v2 13 | - name: Setup go 14 | uses: actions/setup-go@v2 15 | with: 16 | go-version: ${{ matrix.go-version }} 17 | 18 | - name: Download dependencies 19 | run: go mod download 20 | - name: Build 21 | run: go build ./cmd/main.go 22 | - name: Test 23 | run: go test -v ./dataservice 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Dependency directories (remove the comment below to include it) 15 | # vendor/ 16 | 17 | # Misc. 18 | .DS_Store 19 | *.sqlite3 20 | assets/* 21 | !assets/index 22 | livepeer 23 | livepeer_cli 24 | .vscode/ 25 | .idea/ 26 | main 27 | .env 28 | user 29 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.15.2-buster 2 | LABEL maintainer="Rajdeep Bharati " 3 | 4 | RUN apt-get update 5 | RUN apt-cache depends ffmpeg 6 | RUN apt-get install -y ffmpeg 7 | RUN ffmpeg -version 8 | RUN apt-get install -y sqlite3 9 | 10 | RUN mkdir /demuxapp 11 | WORKDIR /demuxapp 12 | 13 | COPY go.mod go.sum ./ 14 | RUN go mod download 15 | COPY . . 16 | RUN go build cmd/main.go 17 | 18 | RUN wget https://github.com/rajdeepbharati/go-livepeer/releases/download/v0.5.10-demux.1/livepeer -P ./livepeerPull/linux 19 | RUN chmod +x ./livepeerPull/linux/livepeer 20 | 21 | ENV IPFS_GATEWAY=${IPFS_GATEWAY} 22 | ENV IPFS_REV_PROXY_ADDR=${IPFS_REV_PROXY_ADDR} 23 | ENV LIVEPEER_COM_API_KEY=${LIVEPEER_COM_API_KEY} 24 | ENV LIVEPEER_PRICING_TOOL=${LIVEPEER_PRICING_TOOL} 25 | ENV PINATA_API_KEY=${PINATA_API_KEY} 26 | ENV PINATA_SECRET_KEY=${PINATA_SECRET_KEY} 27 | ENV POLL_INTERVAL=${POLL_INTERVAL} 28 | ENV PORT=${PORT} 29 | ENV POW_TOKEN=${POW_TOKEN} 30 | ENV POWERGATE_ADDR=${POWERGATE_ADDR} 31 | ENV TRUSTED_MINERS=${TRUSTED_MINERS} 32 | ENV DEMUX_URL=${DEMUX_URL} 33 | ENV MONGO_URI=${MONGO_URI} 34 | 35 | EXPOSE ${PORT} 36 | 37 | CMD [ "./main" ] 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | run: 2 | export LIVEPEER_COM_API_KEY=$(LIVEPEER_COM_API_KEY) 3 | export LIVEPEER_PRICING_TOOL=$(LIVEPEER_PRICING_TOOL) 4 | export POWERGATE_ADDR=$(POWERGATE_ADDR) 5 | export IPFS_REV_PROXY_ADDR=$(IPFS_REV_PROXY_ADDR) 6 | export TRUSTED_MINERS=$(TRUSTED_MINERS) 7 | export POLL_INTERVAL=$(POLL_INTERVAL) 8 | export PORT=$(PORT) 9 | export PINATA_API_KEY=$(PINATA_API_KEY) 10 | export PINATA_SECRET_KEY=$(PINATA_SECRET_KEY) 11 | export IPFS_GATEWAY=$(IPFS_GATEWAY) 12 | export POW_TOKEN=$(POW_TOKEN) 13 | export DEMUX_URL=$(DEMUX_URL) 14 | export MONGO_URI=$(MONGO_URI) 15 | go run cmd/main.go 16 | 17 | build: 18 | go build cmd/main.go 19 | 20 | test: 21 | go test -v ./dataservice 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Demux 2 | 3 | [![Made by BUIDL Labs](https://img.shields.io/badge/made%20by-BUIDL%20Labs-informational.svg)](https://buidllabs.io) 4 | [![Go Report Card](https://goreportcard.com/badge/github.com/buidl-labs/Demux)](https://goreportcard.com/report/github.com/buidl-labs/Demux) 5 | [![GitHub action](https://github.com/buidl-labs/Demux/workflows/Tests/badge.svg)](https://github.com/buidl-labs/Demux/actions) 6 | 7 | A gateway to facilitate a decentralised streaming ecosystem. 8 | 9 | Workflow depicted below: 10 | ![image](https://user-images.githubusercontent.com/24296199/94940994-e923d080-04f1-11eb-8c3d-5aad1f31e91f.png) 11 | 12 | Currently hosted at https://demux.onrender.com/. For authentication credentials, please reach out to us at [saumay@buidllabs.io](saumay@buidllabs.io). 13 | 14 | ## Getting Started 15 | 16 | - Clone the repo: `git clone https://github.com/buidl-labs/Demux` 17 | 18 | ### Using Docker 19 | 20 | - Create a file `.env` and set environment variables (sample present in `Demux/.env.sample`) 21 | - Run your docker daemon. 22 | - Build the docker image: `docker build --tag demux:latest .` 23 | - Run Demux: `docker run -p 8000:8000 --env-file ./.env demux:latest` 24 | 25 |
26 | 27 | ## API Endpoints 28 | 29 | ### At a Glance 30 | 31 | - [`POST /asset`](#post-asset) 32 | - [`POST /fileupload/`](#post-fileuploadasset_id) 33 | - [`GET /upload/`](#get-uploadasset_id) 34 | - [`GET /asset/`](#get-assetasset_id) 35 | - [`POST /pricing`](#post-pricing-wip) **[WIP]** 36 | 37 | ##
38 | 39 | ### `POST /asset` 40 | 41 | Used to create a new _asset_. It returns an `asset_id` and a `url`, where the client can upload a file. 42 | 43 | **Examples** 44 | 45 | - Request: 46 | 47 | ```bash 48 | $ curl http://localhost:8000/asset -u : -d {} 49 | ``` 50 | 51 | Basic authentication must be done by passing the user flag as shown above (colon-separated), or by passing the `Authorization` header. 52 | 53 | For example, in JavaScript: 54 | 55 | ```js 56 | headers: { 57 | 'Authorization' : 'Basic ' + Buffer.from(':', 'utf-8').toString('base64') 58 | } 59 | ``` 60 | 61 | - Response: 62 | 63 | ```json 64 | { 65 | "asset_id": "34d048bb-1076-4937-8b91-6bcda7a6187c", 66 | "url": "http://localhost:8000/fileupload/34d048bb-1076-4937-8b91-6bcda7a6187c" 67 | } 68 | ``` 69 | 70 |
71 | 72 | ### `POST /fileupload/` 73 | 74 | This endpoint is used to upload a video in chunks using [resumable.js](https://github.com/23/resumable.js). 75 | 76 | A frontend client can send the request in the following manner: 77 | 78 | ```js 79 | targetURL = `http://localhost:8000/fileupload/34d048bb-1076-4937-8b91-6bcda7a6187c` 80 | const r = new Resumable({ 81 | target: targetURL 82 | }) 83 | r.addFile(myfile) // myfile is the file (mp4 video) that is being uploaded. 84 | ``` 85 | 86 | Here, the `targetUrl` is the url received after creating an asset using `POST /asset`. 87 | The status of the upload can be tracked using event listeners: 88 | 89 | ```js 90 | r.on('fileAdded', function (file) { 91 | r.upload() 92 | }) 93 | 94 | r.on('progress', function () { 95 | console.log(Math.floor(r.progress() * 100)) 96 | }) 97 | 98 | r.on('fileSuccess', function (file, message) { 99 | console.log('Successfully uploaded', file, 'message:', message) 100 | }) 101 | 102 | r.on('fileError', function (file, message) { 103 | console.log('Error uploading the file:', message) 104 | }) 105 | ``` 106 | 107 | For more details, refer to the [resumable.js docs](https://github.com/23/resumable.js). 108 | 109 |
110 | 111 | ### `GET /upload/` 112 | 113 | This endpoint lets us see the status of an upload. 114 | 115 | **Examples** 116 | 117 | - Request: 118 | 119 | ```bash 120 | $ curl http://localhost:8000/upload/34d048bb-1076-4937-8b91-6bcda7a6187c 121 | ``` 122 | 123 | - Response: 124 | 125 | ```json 126 | { 127 | "asset_id": "34d048bb-1076-4937-8b91-6bcda7a6187c", 128 | "error": false, 129 | "status": true, 130 | "url": "http://localhost:8000/fileupload/34d048bb-1076-4937-8b91-6bcda7a6187c" 131 | } 132 | ``` 133 | 134 | In the response, `status` is initially `false`, and it becomes `true` when the file has been uploaded successfully to Demux (using `/POST /fileupload/`). `error` is `false` by default, and becomes `true` if there is some problem in uploading the file. A frontend client may poll for the upload status to change to `true` before proceeding to the next step in the workflow. 135 | 136 |
137 | 138 | ### `GET /asset/` 139 | 140 | This endpoint gives us the status of an asset (uploaded video) in the pipeline. 141 | 142 | **Examples** 143 | 144 | - Request: 145 | 146 | ```bash 147 | $ curl http://localhost:8000/asset/34d048bb-1076-4937-8b91-6bcda7a6187c 148 | ``` 149 | 150 | - Response: 151 | 152 | ```json 153 | { 154 | "asset_error": false, 155 | "asset_id": "34d048bb-1076-4937-8b91-6bcda7a6187c", 156 | "asset_ready": true, 157 | "asset_status": "pinned to ipfs, attempting to store in filecoin", 158 | "asset_status_code": 3, 159 | "created_at": 1602077805, 160 | "storage_cost": 0, 161 | "storage_cost_estimated": 854019799804687, 162 | "stream_url": "https://demuxipfsrevproxy.onrender.com/ipfs/bafybeiddn2lzoybioi6xh76j7aa67jgxgyyxa42nirfxpo5q477432jzz4/root.m3u8", 163 | "thumbnail": "https://demuxipfsrevproxy.onrender.com/ipfs/bafybeiddn2lzoybioi6xh76j7aa67jgxgyyxa42nirfxpo5q477432jzz4/thumbnail.png", 164 | "transcoding_cost": 0, 165 | "transcoding_cost_estimated": 107880498671623 166 | } 167 | ``` 168 | 169 | **Fields** 170 | 171 | - Response: 172 | 173 | | Field Name | Type | Description | 174 | | -------------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | 175 | | asset_error | `boolean` | Initially its value is false, it will become true in case there is an error. | 176 | | asset_id | `string` | Used to identify an uploaded video. | 177 | | asset_ready | `boolean` | Initially its value is false, it will become true once the video is ready for streaming. | 178 | | asset_status | `string` | Can have five possible values, corresponding to `asset_status_code`
• -1: "asset created"
• 0: "video uploaded successfully"
• 1: "processing in livepeer"
• 2: "attempting to pin to ipfs"
• 3: "pinned to ipfs, attempting to store in filecoin"
• 4: "stored in filecoin" | 179 | | asset_status_code | `int` | Possible values: -1, 0, 1, 2, 3, 4 | 180 | | created_at | `int` | Unix timestamp of asset creation. | 181 | | storage_cost | `int` | Actual storage cost in filecoin network (value in attoFIL). | 182 | | storage_cost_estimated | `int` | Estimated storage cost in filecoin network (value in attoFIL). | 183 | | stream_url | `string` | URL to stream the video. | 184 | | thumbnail | `string` | Thumbnail for the video. | 185 | | transcoding_cost | `int` | Actual transcoding cost in livepeer network (value in WEI). | 186 | | transcoding_cost_estimated | `int` | Estimated transcoding cost in livepeer network (value in WEI). | 187 | 188 |
189 | 190 | ### `POST /pricing` [WIP] 191 | 192 | This is used to estimate the transcoding and storage cost for a given video. 193 | 194 | **Examples** 195 | 196 | - Request: 197 | 198 | ```bash 199 | $ curl http://localhost:8000/pricing -d "{\"video_duration\":60, \"video_file_size\":28, \"storage_duration\":2628005}" 200 | ``` 201 | 202 | - Response: 203 | 204 | ```json 205 | { 206 | "storage_cost_estimated": 1562410068450, 207 | "transcoding_cost_estimated": 170337629481511 208 | } 209 | ``` 210 | 211 | **Fields** 212 | 213 | - Request: 214 | 215 | | Field Name | Type | Description | 216 | | ---------------- | ----- | ---------------------------------------------------------------------------------------------------------------------------------- | 217 | | video_duration | `int` | Duration of the video in seconds. Its value must be greater than `0`. | 218 | | video_file_size | `int` | Size of the video in MiB (1 MiB = 2^20 B). | 219 | | storage_duration | `int` | Duration in seconds for which you want to store the video stream in filecoin. Its value must be between `2628003` and `315360000`. | 220 | 221 | - Response: 222 | 223 | | Field Name | Type | Description | 224 | | -------------------------- | ----- | -------------------------------------------------------------- | 225 | | storage_cost_estimated | `int` | Estimated storage cost in filecoin network (value in attoFIL). | 226 | | transcoding_cost_estimated | `int` | Estimated transcoding cost in livepeer network (value in WEI). | 227 | 228 |
229 | 230 | ## Requirements 231 | 232 | - go 1.15.2 233 | - ffmpeg 234 | - mongodb 235 | -------------------------------------------------------------------------------- /assets/index: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/buidl-labs/Demux/dcf02bf6ed2e13b62c535cfadc708fbbba318d96/assets/index -------------------------------------------------------------------------------- /cmd/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | 6 | "github.com/buidl-labs/Demux/dataservice" 7 | "github.com/buidl-labs/Demux/server" 8 | // "github.com/buidl-labs/Demux/util" 9 | ) 10 | 11 | func main() { 12 | db := dataservice.InitMongoClient() 13 | // go util.RunPoller(db) 14 | server.StartServer(":" + os.Getenv("PORT"), db) 15 | } 16 | -------------------------------------------------------------------------------- /config/profiles.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "my-stream", 3 | "profiles": [ 4 | { 5 | "name": "1080p", 6 | "bitrate": 6000000, 7 | "fps": 30, 8 | "width": 1920, 9 | "height": 1080 10 | }, 11 | { 12 | "name": "720p", 13 | "bitrate": 2000000, 14 | "fps": 30, 15 | "width": 1280, 16 | "height": 720 17 | }, 18 | { 19 | "name": "360p", 20 | "bitrate": 500000, 21 | "fps": 30, 22 | "width": 640, 23 | "height": 360 24 | } 25 | ] 26 | } 27 | -------------------------------------------------------------------------------- /dataservice/asset.go: -------------------------------------------------------------------------------- 1 | package dataservice 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/buidl-labs/Demux/model" 7 | 8 | log "github.com/sirupsen/logrus" 9 | 10 | "go.mongodb.org/mongo-driver/bson" 11 | "go.mongodb.org/mongo-driver/bson/primitive" 12 | ) 13 | 14 | // AssetDatabase provides the asset db operations. 15 | type AssetDatabase interface { 16 | InsertAsset(model.Asset) error 17 | GetAsset(string) (model.Asset, error) 18 | IfAssetExists(string) bool 19 | UpdateAssetStatus(string, int32, string, bool) error 20 | UpdateAssetReady(string, bool) error 21 | UpdateStreamURL(string, string) error 22 | UpdateThumbnail(string, string) error 23 | } 24 | 25 | type assetDatabase struct { 26 | db DatabaseHelper 27 | } 28 | 29 | // NewAssetDatabase returns an instance of AssetDatabase. 30 | func NewAssetDatabase(db DatabaseHelper) AssetDatabase { 31 | return &assetDatabase{ 32 | db: db, 33 | } 34 | } 35 | 36 | func (a *assetDatabase) InsertAsset(asset model.Asset) error { 37 | insertResult, err := a.db.Collection("asset").InsertOne(context.Background(), asset) 38 | if err != nil { 39 | log.Error("Inserting an asset: ", err) 40 | return err 41 | } 42 | log.Info("Inserted an asset: ", insertResult) 43 | return nil 44 | } 45 | 46 | func (a *assetDatabase) GetAsset(assetID string) (model.Asset, error) { 47 | result := model.Asset{} 48 | filter := bson.D{primitive.E{Key: "_id", Value: assetID}} 49 | err := a.db.Collection("asset").FindOne(context.Background(), filter).Decode(&result) 50 | if err != nil { 51 | log.Error("Getting asset: ", err) 52 | return result, err 53 | } 54 | log.Info("Getting asset: ", result.AssetID) 55 | return result, nil 56 | } 57 | 58 | func (a *assetDatabase) IfAssetExists(assetID string) bool { 59 | result := model.Asset{} 60 | filter := bson.D{primitive.E{Key: "_id", Value: assetID}} 61 | err := a.db.Collection("asset").FindOne(context.Background(), filter).Decode(&result) 62 | if err != nil { 63 | log.Error("Checking if asset exists: ", err) 64 | return false 65 | } 66 | log.Info("Checking if asset exists: ", true) 67 | return true 68 | } 69 | 70 | func (a *assetDatabase) UpdateAssetStatus(assetID string, assetStatusCode int32, assetStatus string, assetError bool) error { 71 | filter := bson.M{"_id": assetID} 72 | update := bson.M{"$set": bson.M{ 73 | "asset_status_code": assetStatusCode, 74 | "asset_status": assetStatus, 75 | "asset_error": assetError, 76 | }} 77 | result, err := a.db.Collection("asset").UpdateOne(context.Background(), filter, update) 78 | if err != nil { 79 | log.Error("Updating asset status: ", err) 80 | return err 81 | } 82 | log.Info("Updated asset status: ", result) 83 | return nil 84 | } 85 | 86 | func (a *assetDatabase) UpdateAssetReady(assetID string, assetReady bool) error { 87 | filter := bson.M{"_id": assetID} 88 | update := bson.M{"$set": bson.M{ 89 | "asset_ready": assetReady, 90 | }} 91 | result, err := a.db.Collection("asset").UpdateOne(context.Background(), filter, update) 92 | if err != nil { 93 | log.Error("Updating asset ready status: ", err) 94 | return err 95 | } 96 | log.Info("Updating asset ready status: ", result) 97 | return nil 98 | } 99 | 100 | func (a *assetDatabase) UpdateStreamURL(assetID string, streamURL string) error { 101 | filter := bson.M{"_id": assetID} 102 | update := bson.M{"$set": bson.M{ 103 | "stream_url": streamURL, 104 | }} 105 | result, err := a.db.Collection("asset").UpdateOne(context.Background(), filter, update) 106 | if err != nil { 107 | log.Error("Updating streamURL: ", err) 108 | return err 109 | } 110 | log.Info("Updating streamURL: ", result) 111 | return nil 112 | } 113 | 114 | func (a *assetDatabase) UpdateThumbnail(assetID string, thumbnail string) error { 115 | filter := bson.M{"_id": assetID} 116 | update := bson.M{"$set": bson.M{ 117 | "thumbnail": thumbnail, 118 | }} 119 | result, err := a.db.Collection("asset").UpdateOne(context.Background(), filter, update) 120 | if err != nil { 121 | log.Error("Updating thumbnail: ", result) 122 | return err 123 | } 124 | log.Info("Updating thumbnail: ", result) 125 | return nil 126 | } 127 | -------------------------------------------------------------------------------- /dataservice/asset_test.go: -------------------------------------------------------------------------------- 1 | package dataservice_test 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/buidl-labs/Demux/dataservice" 7 | "github.com/buidl-labs/Demux/dataservice/mocks" 8 | "github.com/buidl-labs/Demux/model" 9 | 10 | "github.com/stretchr/testify/assert" 11 | ) 12 | 13 | func TestNewAssetDatabase(t *testing.T) { 14 | dbClient, err := dataservice.NewClient(uri) 15 | assert.NoError(t, err) 16 | 17 | db := dataservice.NewDatabase(dbName, dbClient) 18 | 19 | assetDB := dataservice.NewAssetDatabase(db) 20 | 21 | assert.NotEmpty(t, assetDB) 22 | } 23 | 24 | func TestGetAsset(t *testing.T) { 25 | assetDba := &mocks.AssetDatabase{} 26 | 27 | asset1, err := assetDba.GetAsset("1b2e976a-983d-4845-967a-f60b33c82869") 28 | assert.NoError(t, err) 29 | assert.Equal(t, model.Asset{ 30 | AssetID: "1b2e976a-983d-4845-967a-f60b33c82869", 31 | AssetReady: false, 32 | AssetStatusCode: 0, 33 | AssetStatus: "asset created", 34 | AssetError: false, 35 | CreatedAt: 1605030069, 36 | Thumbnail: "", 37 | }, asset1) 38 | 39 | asset2, err := assetDba.GetAsset("some-wrong-asset-id") 40 | assert.EqualError(t, err, "couldn't find asset") 41 | assert.Equal(t, model.Asset{}, asset2) 42 | } 43 | 44 | func TestInsertAsset(t *testing.T) { 45 | assetDba := &mocks.AssetDatabase{} 46 | 47 | err := assetDba.InsertAsset(model.Asset{ 48 | AssetID: "1b2e976a-983d-4845-967a-f60b33c82869", 49 | AssetReady: false, 50 | AssetStatusCode: 0, 51 | AssetStatus: "asset created", 52 | AssetError: false, 53 | CreatedAt: 1605030069, 54 | Thumbnail: "", 55 | }) 56 | assert.NoError(t, err) 57 | } 58 | -------------------------------------------------------------------------------- /dataservice/dataservice.go: -------------------------------------------------------------------------------- 1 | package dataservice 2 | 3 | import ( 4 | "context" 5 | "os" 6 | 7 | log "github.com/sirupsen/logrus" 8 | 9 | "go.mongodb.org/mongo-driver/mongo" 10 | "go.mongodb.org/mongo-driver/mongo/options" 11 | ) 12 | 13 | var ( 14 | dbName = "demux" 15 | connectionString = os.Getenv("MONGO_URI") 16 | assetCollection *mongo.Collection 17 | uploadCollection *mongo.Collection 18 | transcodingDealCollection *mongo.Collection 19 | storageDealCollection *mongo.Collection 20 | userCollection *mongo.Collection 21 | sizeRatioCollection *mongo.Collection 22 | meanSizeRatioCollection *mongo.Collection 23 | ) 24 | 25 | // DatabaseHelper is an abstraction of the mongodb client instance. 26 | type DatabaseHelper interface { 27 | Collection(name string) CollectionHelper 28 | Client() ClientHelper 29 | } 30 | 31 | // CollectionHelper provides access to basic mongodb collection operations. 32 | type CollectionHelper interface { 33 | FindOne(context.Context, interface{}) SingleResultHelper 34 | Find(ctx context.Context, filter interface{}) (*mongo.Cursor, error) 35 | InsertOne(context.Context, interface{}) (interface{}, error) 36 | UpdateOne(context.Context, interface{}, interface{}) (int64, error) 37 | DeleteOne(ctx context.Context, filter interface{}) (int64, error) 38 | } 39 | 40 | // SingleResultHelper provides access to the mongo Decode function for a single result. 41 | type SingleResultHelper interface { 42 | Decode(v interface{}) error 43 | } 44 | 45 | // ClientHelper provides access to methods to control the db client. 46 | type ClientHelper interface { 47 | Database(string) DatabaseHelper 48 | Connect() error 49 | StartSession() (mongo.Session, error) 50 | } 51 | 52 | type mongoClient struct { 53 | cl *mongo.Client 54 | } 55 | 56 | type mongoDatabase struct { 57 | db *mongo.Database 58 | } 59 | 60 | type mongoCollection struct { 61 | coll *mongo.Collection 62 | } 63 | 64 | type mongoSingleResult struct { 65 | sr *mongo.SingleResult 66 | } 67 | 68 | type mongoSession struct { 69 | mongo.Session 70 | } 71 | 72 | // NewClient returns a ClientHelper for a given MONGO_URI. 73 | func NewClient(uri string) (ClientHelper, error) { 74 | c, err := mongo.NewClient(options.Client().ApplyURI(uri)) 75 | return &mongoClient{cl: c}, err 76 | } 77 | 78 | // NewDatabase returns a DatabaseHelper for a given db name and ClientHelper. 79 | func NewDatabase(dbName string, client ClientHelper) DatabaseHelper { 80 | return client.Database(dbName) 81 | } 82 | 83 | func (mc *mongoClient) Database(dbName string) DatabaseHelper { 84 | db := mc.cl.Database(dbName) 85 | return &mongoDatabase{db: db} 86 | } 87 | 88 | func (mc *mongoClient) StartSession() (mongo.Session, error) { 89 | session, err := mc.cl.StartSession() 90 | return &mongoSession{session}, err 91 | } 92 | 93 | func (mc *mongoClient) Connect() error { 94 | // mongo client does not use context on connect method. There is a ticket 95 | // with a request to deprecate this functionality and another one with 96 | // explanation why it could be useful in synchronous requests. 97 | // https://jira.mongodb.org/browse/GODRIVER-1031 98 | // https://jira.mongodb.org/browse/GODRIVER-979 99 | return mc.cl.Connect(nil) 100 | } 101 | 102 | func (md *mongoDatabase) Collection(colName string) CollectionHelper { 103 | collection := md.db.Collection(colName) 104 | return &mongoCollection{coll: collection} 105 | } 106 | 107 | func (md *mongoDatabase) Client() ClientHelper { 108 | client := md.db.Client() 109 | return &mongoClient{cl: client} 110 | } 111 | 112 | func (mc *mongoCollection) FindOne(ctx context.Context, filter interface{}) SingleResultHelper { 113 | singleResult := mc.coll.FindOne(ctx, filter) 114 | return &mongoSingleResult{sr: singleResult} 115 | } 116 | 117 | func (mc *mongoCollection) Find(ctx context.Context, filter interface{}) (*mongo.Cursor, error) { 118 | cur, err := mc.coll.Find(ctx, filter) 119 | return cur, err 120 | } 121 | 122 | func (mc *mongoCollection) InsertOne(ctx context.Context, document interface{}) (interface{}, error) { 123 | id, err := mc.coll.InsertOne(ctx, document) 124 | return id.InsertedID, err 125 | } 126 | 127 | func (mc *mongoCollection) UpdateOne(ctx context.Context, filter interface{}, update interface{}) (int64, error) { 128 | result, err := mc.coll.UpdateOne(ctx, filter, update) 129 | return result.ModifiedCount, err 130 | } 131 | 132 | func (mc *mongoCollection) DeleteOne(ctx context.Context, filter interface{}) (int64, error) { 133 | count, err := mc.coll.DeleteOne(ctx, filter) 134 | return count.DeletedCount, err 135 | } 136 | 137 | func (sr *mongoSingleResult) Decode(v interface{}) error { 138 | return sr.sr.Decode(v) 139 | } 140 | 141 | // InitMongoClient initializes the mongo client. 142 | func InitMongoClient() DatabaseHelper { 143 | 144 | client, err := NewClient(connectionString) 145 | if err != nil { 146 | log.Fatal("mdb conn: ", err) 147 | } 148 | err = client.Connect() 149 | if err != nil { 150 | log.Fatal("Failed to connect to database: ", err) 151 | } 152 | 153 | db := NewDatabase("demux", client) 154 | 155 | return db 156 | 157 | } 158 | -------------------------------------------------------------------------------- /dataservice/dataservice_test.go: -------------------------------------------------------------------------------- 1 | package dataservice_test 2 | 3 | import ( 4 | "errors" 5 | "testing" 6 | 7 | "github.com/buidl-labs/Demux/dataservice" 8 | "github.com/buidl-labs/Demux/dataservice/mocks" 9 | 10 | "github.com/stretchr/testify/assert" 11 | ) 12 | 13 | var dbName = "demux" 14 | var uri = "mongodb://127.0.0.1:27017" 15 | 16 | // TestNewDatabase tests new database creation. 17 | func TestNewDatabase(t *testing.T) { 18 | dbClient, err := dataservice.NewClient(uri) 19 | assert.NoError(t, err) 20 | 21 | db := dataservice.NewDatabase(dbName, dbClient) 22 | 23 | assert.NotEmpty(t, db) 24 | } 25 | 26 | // TestStartSession tests starting session. 27 | func TestStartSession(t *testing.T) { 28 | // The code below does not fall under the cover tool as we are testing mocks 29 | // and in order to test the actual code, we would need to expose internal 30 | // structures and create interfaces for them. In addition to this it would 31 | // require to mock them as well. 32 | 33 | // Of course we can use this approach to achieve 100% coverage but it is not 34 | // actually worth it to test mongo functionality itself. For such cases it 35 | // is better to use integration tests, but thats another topic. 36 | 37 | var db dataservice.DatabaseHelper 38 | var client dataservice.ClientHelper 39 | 40 | // db = &MockDatabaseHelper{} // can be used as db = &mocks.DatabaseHelper{} 41 | db = &mocks.DatabaseHelper{} 42 | client = &mocks.ClientHelper{} 43 | 44 | client.(*mocks.ClientHelper).On("StartSession").Return(nil, errors.New("mocked-error")) 45 | 46 | db.(*mocks.DatabaseHelper).On("Client").Return(client) 47 | 48 | // As we do not actual start any session then we do not need to check it. 49 | // It is possible to mock session interface and check for custom conditions 50 | // But this creates huge overhead to the unnecessary functionality. 51 | _, err := db.Client().StartSession() 52 | 53 | assert.EqualError(t, err, "mocked-error") 54 | } 55 | -------------------------------------------------------------------------------- /dataservice/mean_size_ratio.go: -------------------------------------------------------------------------------- 1 | package dataservice 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/buidl-labs/Demux/model" 7 | 8 | log "github.com/sirupsen/logrus" 9 | 10 | "go.mongodb.org/mongo-driver/bson" 11 | "go.mongodb.org/mongo-driver/bson/primitive" 12 | ) 13 | 14 | // MeanSizeRatioDatabase provides the msr db operations. 15 | type MeanSizeRatioDatabase interface { 16 | InsertMeanSizeRatio(model.SizeRatio) error 17 | GetMeanSizeRatio() (model.MeanSizeRatio, error) 18 | UpdateMeanSizeRatio(float64, float64, uint64) error 19 | } 20 | 21 | type meanSizeRatioDatabase struct { 22 | db DatabaseHelper 23 | } 24 | 25 | // NewMeanSizeRatioDatabase returns an instance of MeanSizeRatioDatabase. 26 | func NewMeanSizeRatioDatabase(db DatabaseHelper) MeanSizeRatioDatabase { 27 | return &meanSizeRatioDatabase{ 28 | db: db, 29 | } 30 | } 31 | 32 | func (msr *meanSizeRatioDatabase) InsertMeanSizeRatio(meanSizeRatio model.SizeRatio) error { 33 | insertResult, err := msr.db.Collection("meanSizeRatio").InsertOne(context.Background(), meanSizeRatio) 34 | if err != nil { 35 | log.Error("Inserting a meanSizeRatio:", err) 36 | return err 37 | } 38 | log.Info("Inserted a meanSizeRatio: ", insertResult) 39 | return nil 40 | } 41 | 42 | func (msr *meanSizeRatioDatabase) GetMeanSizeRatio() (model.MeanSizeRatio, error) { 43 | result := model.MeanSizeRatio{} 44 | filter := bson.D{primitive.E{Key: "_id", Value: 1}} 45 | err := msr.db.Collection("meanSizeRatio").FindOne(context.Background(), filter).Decode(&result) 46 | if err != nil { 47 | log.Error("Getting meanSizeRatio: ", err) 48 | return result, err 49 | } 50 | log.Info("Getting meanSizeRatio: ", result.ID) 51 | return result, nil 52 | } 53 | 54 | func (msr *meanSizeRatioDatabase) UpdateMeanSizeRatio(ratio float64, ratioSum float64, count uint64) error { 55 | filter := bson.M{"_id": 1} 56 | update := bson.M{"$set": bson.M{ 57 | "ratio": ratio, 58 | "ratio_sum": ratioSum, 59 | "count": count, 60 | }} 61 | result, err := msr.db.Collection("meanSizeRatio").UpdateOne(context.Background(), filter, update) 62 | if err != nil { 63 | log.Error("Updating meanSizeRatio: ", err) 64 | return err 65 | } 66 | log.Info("Updating meanSizeRatio: ", result) 67 | return nil 68 | } 69 | -------------------------------------------------------------------------------- /dataservice/mocks/AssetDatabase.go: -------------------------------------------------------------------------------- 1 | // Code generated by mockery v2.4.0-beta. DO NOT EDIT. 2 | 3 | package mocks 4 | 5 | import ( 6 | "fmt" 7 | 8 | model "github.com/buidl-labs/Demux/model" 9 | mock "github.com/stretchr/testify/mock" 10 | ) 11 | 12 | // AssetDatabase is an autogenerated mock type for the AssetDatabase type 13 | type AssetDatabase struct { 14 | mock.Mock 15 | } 16 | 17 | // GetAsset provides a mock function with given fields: _a0 18 | func (_m *AssetDatabase) GetAsset(_a0 string) (model.Asset, error) { 19 | asset := model.Asset{ 20 | AssetID: "1b2e976a-983d-4845-967a-f60b33c82869", 21 | AssetReady: false, 22 | AssetStatusCode: 0, 23 | AssetStatus: "asset created", 24 | AssetError: false, 25 | CreatedAt: 1605030069, 26 | Thumbnail: "", 27 | } 28 | 29 | if _a0 == asset.AssetID { 30 | return asset, nil 31 | } 32 | 33 | return model.Asset{}, fmt.Errorf("couldn't find asset") 34 | } 35 | 36 | // IfAssetExists provides a mock function with given fields: _a0 37 | func (_m *AssetDatabase) IfAssetExists(_a0 string) bool { 38 | asset := model.Asset{ 39 | AssetID: "1b2e976a-983d-4845-967a-f60b33c82869", 40 | AssetReady: false, 41 | AssetStatusCode: 0, 42 | AssetStatus: "asset created", 43 | AssetError: false, 44 | CreatedAt: 1605030069, 45 | Thumbnail: "", 46 | } 47 | 48 | if _a0 == asset.AssetID { 49 | return true 50 | } 51 | 52 | return false 53 | } 54 | 55 | // InsertAsset provides a mock function with given fields: _a0 56 | func (_m *AssetDatabase) InsertAsset(_a0 model.Asset) error { 57 | return nil 58 | } 59 | 60 | // UpdateAssetReady provides a mock function with given fields: _a0, _a1 61 | func (_m *AssetDatabase) UpdateAssetReady(_a0 string, _a1 bool) error { 62 | ret := _m.Called(_a0, _a1) 63 | 64 | var r0 error 65 | if rf, ok := ret.Get(0).(func(string, bool) error); ok { 66 | r0 = rf(_a0, _a1) 67 | } else { 68 | r0 = ret.Error(0) 69 | } 70 | 71 | return r0 72 | } 73 | 74 | // UpdateAssetStatus provides a mock function with given fields: _a0, _a1, _a2, _a3 75 | func (_m *AssetDatabase) UpdateAssetStatus(_a0 string, _a1 int32, _a2 string, _a3 bool) error { 76 | ret := _m.Called(_a0, _a1, _a2, _a3) 77 | 78 | var r0 error 79 | if rf, ok := ret.Get(0).(func(string, int32, string, bool) error); ok { 80 | r0 = rf(_a0, _a1, _a2, _a3) 81 | } else { 82 | r0 = ret.Error(0) 83 | } 84 | 85 | return r0 86 | } 87 | 88 | // UpdateStreamURL provides a mock function with given fields: _a0, _a1 89 | func (_m *AssetDatabase) UpdateStreamURL(_a0 string, _a1 string) error { 90 | ret := _m.Called(_a0, _a1) 91 | 92 | var r0 error 93 | if rf, ok := ret.Get(0).(func(string, string) error); ok { 94 | r0 = rf(_a0, _a1) 95 | } else { 96 | r0 = ret.Error(0) 97 | } 98 | 99 | return r0 100 | } 101 | 102 | // UpdateThumbnail provides a mock function with given fields: _a0, _a1 103 | func (_m *AssetDatabase) UpdateThumbnail(_a0 string, _a1 string) error { 104 | ret := _m.Called(_a0, _a1) 105 | 106 | var r0 error 107 | if rf, ok := ret.Get(0).(func(string, string) error); ok { 108 | r0 = rf(_a0, _a1) 109 | } else { 110 | r0 = ret.Error(0) 111 | } 112 | 113 | return r0 114 | } 115 | -------------------------------------------------------------------------------- /dataservice/mocks/ClientHelper.go: -------------------------------------------------------------------------------- 1 | // Code generated by mockery v2.4.0-beta. DO NOT EDIT. 2 | 3 | package mocks 4 | 5 | import ( 6 | dataservice "github.com/buidl-labs/Demux/dataservice" 7 | mock "github.com/stretchr/testify/mock" 8 | 9 | mongo "go.mongodb.org/mongo-driver/mongo" 10 | ) 11 | 12 | // ClientHelper is an autogenerated mock type for the ClientHelper type 13 | type ClientHelper struct { 14 | mock.Mock 15 | } 16 | 17 | // Connect provides a mock function with given fields: 18 | func (_m *ClientHelper) Connect() error { 19 | ret := _m.Called() 20 | 21 | var r0 error 22 | if rf, ok := ret.Get(0).(func() error); ok { 23 | r0 = rf() 24 | } else { 25 | r0 = ret.Error(0) 26 | } 27 | 28 | return r0 29 | } 30 | 31 | // Database provides a mock function with given fields: _a0 32 | func (_m *ClientHelper) Database(_a0 string) dataservice.DatabaseHelper { 33 | ret := _m.Called(_a0) 34 | 35 | var r0 dataservice.DatabaseHelper 36 | if rf, ok := ret.Get(0).(func(string) dataservice.DatabaseHelper); ok { 37 | r0 = rf(_a0) 38 | } else { 39 | if ret.Get(0) != nil { 40 | r0 = ret.Get(0).(dataservice.DatabaseHelper) 41 | } 42 | } 43 | 44 | return r0 45 | } 46 | 47 | // StartSession provides a mock function with given fields: 48 | func (_m *ClientHelper) StartSession() (mongo.Session, error) { 49 | ret := _m.Called() 50 | 51 | var r0 mongo.Session 52 | if rf, ok := ret.Get(0).(func() mongo.Session); ok { 53 | r0 = rf() 54 | } else { 55 | if ret.Get(0) != nil { 56 | r0 = ret.Get(0).(mongo.Session) 57 | } 58 | } 59 | 60 | var r1 error 61 | if rf, ok := ret.Get(1).(func() error); ok { 62 | r1 = rf() 63 | } else { 64 | r1 = ret.Error(1) 65 | } 66 | 67 | return r0, r1 68 | } 69 | -------------------------------------------------------------------------------- /dataservice/mocks/CollectionHelper.go: -------------------------------------------------------------------------------- 1 | // Code generated by mockery v2.4.0-beta. DO NOT EDIT. 2 | 3 | package mocks 4 | 5 | import ( 6 | context "context" 7 | 8 | dataservice "github.com/buidl-labs/Demux/dataservice" 9 | mock "github.com/stretchr/testify/mock" 10 | 11 | mongo "go.mongodb.org/mongo-driver/mongo" 12 | ) 13 | 14 | // CollectionHelper is an autogenerated mock type for the CollectionHelper type 15 | type CollectionHelper struct { 16 | mock.Mock 17 | } 18 | 19 | // DeleteOne provides a mock function with given fields: ctx, filter 20 | func (_m *CollectionHelper) DeleteOne(ctx context.Context, filter interface{}) (int64, error) { 21 | ret := _m.Called(ctx, filter) 22 | 23 | var r0 int64 24 | if rf, ok := ret.Get(0).(func(context.Context, interface{}) int64); ok { 25 | r0 = rf(ctx, filter) 26 | } else { 27 | r0 = ret.Get(0).(int64) 28 | } 29 | 30 | var r1 error 31 | if rf, ok := ret.Get(1).(func(context.Context, interface{}) error); ok { 32 | r1 = rf(ctx, filter) 33 | } else { 34 | r1 = ret.Error(1) 35 | } 36 | 37 | return r0, r1 38 | } 39 | 40 | // Find provides a mock function with given fields: ctx, filter 41 | func (_m *CollectionHelper) Find(ctx context.Context, filter interface{}) (*mongo.Cursor, error) { 42 | ret := _m.Called(ctx, filter) 43 | 44 | var r0 *mongo.Cursor 45 | if rf, ok := ret.Get(0).(func(context.Context, interface{}) *mongo.Cursor); ok { 46 | r0 = rf(ctx, filter) 47 | } else { 48 | if ret.Get(0) != nil { 49 | r0 = ret.Get(0).(*mongo.Cursor) 50 | } 51 | } 52 | 53 | var r1 error 54 | if rf, ok := ret.Get(1).(func(context.Context, interface{}) error); ok { 55 | r1 = rf(ctx, filter) 56 | } else { 57 | r1 = ret.Error(1) 58 | } 59 | 60 | return r0, r1 61 | } 62 | 63 | // FindOne provides a mock function with given fields: _a0, _a1 64 | func (_m *CollectionHelper) FindOne(_a0 context.Context, _a1 interface{}) dataservice.SingleResultHelper { 65 | ret := _m.Called(_a0, _a1) 66 | 67 | var r0 dataservice.SingleResultHelper 68 | if rf, ok := ret.Get(0).(func(context.Context, interface{}) dataservice.SingleResultHelper); ok { 69 | r0 = rf(_a0, _a1) 70 | } else { 71 | if ret.Get(0) != nil { 72 | r0 = ret.Get(0).(dataservice.SingleResultHelper) 73 | } 74 | } 75 | 76 | return r0 77 | } 78 | 79 | // InsertOne provides a mock function with given fields: _a0, _a1 80 | func (_m *CollectionHelper) InsertOne(_a0 context.Context, _a1 interface{}) (interface{}, error) { 81 | ret := _m.Called(_a0, _a1) 82 | 83 | var r0 interface{} 84 | if rf, ok := ret.Get(0).(func(context.Context, interface{}) interface{}); ok { 85 | r0 = rf(_a0, _a1) 86 | } else { 87 | if ret.Get(0) != nil { 88 | r0 = ret.Get(0).(interface{}) 89 | } 90 | } 91 | 92 | var r1 error 93 | if rf, ok := ret.Get(1).(func(context.Context, interface{}) error); ok { 94 | r1 = rf(_a0, _a1) 95 | } else { 96 | r1 = ret.Error(1) 97 | } 98 | 99 | return r0, r1 100 | } 101 | 102 | // UpdateOne provides a mock function with given fields: _a0, _a1, _a2 103 | func (_m *CollectionHelper) UpdateOne(_a0 context.Context, _a1 interface{}, _a2 interface{}) (int64, error) { 104 | ret := _m.Called(_a0, _a1, _a2) 105 | 106 | var r0 int64 107 | if rf, ok := ret.Get(0).(func(context.Context, interface{}, interface{}) int64); ok { 108 | r0 = rf(_a0, _a1, _a2) 109 | } else { 110 | r0 = ret.Get(0).(int64) 111 | } 112 | 113 | var r1 error 114 | if rf, ok := ret.Get(1).(func(context.Context, interface{}, interface{}) error); ok { 115 | r1 = rf(_a0, _a1, _a2) 116 | } else { 117 | r1 = ret.Error(1) 118 | } 119 | 120 | return r0, r1 121 | } 122 | -------------------------------------------------------------------------------- /dataservice/mocks/DatabaseHelper.go: -------------------------------------------------------------------------------- 1 | // Code generated by mockery v2.4.0-beta. DO NOT EDIT. 2 | 3 | package mocks 4 | 5 | import ( 6 | dataservice "github.com/buidl-labs/Demux/dataservice" 7 | mock "github.com/stretchr/testify/mock" 8 | ) 9 | 10 | // DatabaseHelper is an autogenerated mock type for the DatabaseHelper type 11 | type DatabaseHelper struct { 12 | mock.Mock 13 | } 14 | 15 | // Client provides a mock function with given fields: 16 | func (_m *DatabaseHelper) Client() dataservice.ClientHelper { 17 | ret := _m.Called() 18 | 19 | var r0 dataservice.ClientHelper 20 | if rf, ok := ret.Get(0).(func() dataservice.ClientHelper); ok { 21 | r0 = rf() 22 | } else { 23 | if ret.Get(0) != nil { 24 | r0 = ret.Get(0).(dataservice.ClientHelper) 25 | } 26 | } 27 | 28 | return r0 29 | } 30 | 31 | // Collection provides a mock function with given fields: name 32 | func (_m *DatabaseHelper) Collection(name string) dataservice.CollectionHelper { 33 | ret := _m.Called(name) 34 | 35 | var r0 dataservice.CollectionHelper 36 | if rf, ok := ret.Get(0).(func(string) dataservice.CollectionHelper); ok { 37 | r0 = rf(name) 38 | } else { 39 | if ret.Get(0) != nil { 40 | r0 = ret.Get(0).(dataservice.CollectionHelper) 41 | } 42 | } 43 | 44 | return r0 45 | } 46 | -------------------------------------------------------------------------------- /dataservice/mocks/MeanSizeRatioDatabase.go: -------------------------------------------------------------------------------- 1 | // Code generated by mockery v2.4.0-beta. DO NOT EDIT. 2 | 3 | package mocks 4 | 5 | import ( 6 | model "github.com/buidl-labs/Demux/model" 7 | mock "github.com/stretchr/testify/mock" 8 | ) 9 | 10 | // MeanSizeRatioDatabase is an autogenerated mock type for the MeanSizeRatioDatabase type 11 | type MeanSizeRatioDatabase struct { 12 | mock.Mock 13 | } 14 | 15 | // GetMeanSizeRatio provides a mock function with given fields: 16 | func (_m *MeanSizeRatioDatabase) GetMeanSizeRatio() (model.MeanSizeRatio, error) { 17 | ret := _m.Called() 18 | 19 | var r0 model.MeanSizeRatio 20 | if rf, ok := ret.Get(0).(func() model.MeanSizeRatio); ok { 21 | r0 = rf() 22 | } else { 23 | r0 = ret.Get(0).(model.MeanSizeRatio) 24 | } 25 | 26 | var r1 error 27 | if rf, ok := ret.Get(1).(func() error); ok { 28 | r1 = rf() 29 | } else { 30 | r1 = ret.Error(1) 31 | } 32 | 33 | return r0, r1 34 | } 35 | 36 | // InsertMeanSizeRatio provides a mock function with given fields: _a0 37 | func (_m *MeanSizeRatioDatabase) InsertMeanSizeRatio(_a0 model.SizeRatio) error { 38 | ret := _m.Called(_a0) 39 | 40 | var r0 error 41 | if rf, ok := ret.Get(0).(func(model.SizeRatio) error); ok { 42 | r0 = rf(_a0) 43 | } else { 44 | r0 = ret.Error(0) 45 | } 46 | 47 | return r0 48 | } 49 | 50 | // UpdateMeanSizeRatio provides a mock function with given fields: _a0, _a1, _a2 51 | func (_m *MeanSizeRatioDatabase) UpdateMeanSizeRatio(_a0 float64, _a1 float64, _a2 uint64) error { 52 | ret := _m.Called(_a0, _a1, _a2) 53 | 54 | var r0 error 55 | if rf, ok := ret.Get(0).(func(float64, float64, uint64) error); ok { 56 | r0 = rf(_a0, _a1, _a2) 57 | } else { 58 | r0 = ret.Error(0) 59 | } 60 | 61 | return r0 62 | } 63 | -------------------------------------------------------------------------------- /dataservice/mocks/SingleResultHelper.go: -------------------------------------------------------------------------------- 1 | // Code generated by mockery v2.4.0-beta. DO NOT EDIT. 2 | 3 | package mocks 4 | 5 | import mock "github.com/stretchr/testify/mock" 6 | 7 | // SingleResultHelper is an autogenerated mock type for the SingleResultHelper type 8 | type SingleResultHelper struct { 9 | mock.Mock 10 | } 11 | 12 | // Decode provides a mock function with given fields: v 13 | func (_m *SingleResultHelper) Decode(v interface{}) error { 14 | ret := _m.Called(v) 15 | 16 | var r0 error 17 | if rf, ok := ret.Get(0).(func(interface{}) error); ok { 18 | r0 = rf(v) 19 | } else { 20 | r0 = ret.Error(0) 21 | } 22 | 23 | return r0 24 | } 25 | -------------------------------------------------------------------------------- /dataservice/mocks/SizeRatioDatabase.go: -------------------------------------------------------------------------------- 1 | // Code generated by mockery v2.4.0-beta. DO NOT EDIT. 2 | 3 | package mocks 4 | 5 | import ( 6 | model "github.com/buidl-labs/Demux/model" 7 | mock "github.com/stretchr/testify/mock" 8 | ) 9 | 10 | // SizeRatioDatabase is an autogenerated mock type for the SizeRatioDatabase type 11 | type SizeRatioDatabase struct { 12 | mock.Mock 13 | } 14 | 15 | // InsertSizeRatio provides a mock function with given fields: _a0 16 | func (_m *SizeRatioDatabase) InsertSizeRatio(_a0 model.SizeRatio) error { 17 | ret := _m.Called(_a0) 18 | 19 | var r0 error 20 | if rf, ok := ret.Get(0).(func(model.SizeRatio) error); ok { 21 | r0 = rf(_a0) 22 | } else { 23 | r0 = ret.Error(0) 24 | } 25 | 26 | return r0 27 | } 28 | -------------------------------------------------------------------------------- /dataservice/mocks/StorageDealDatabase.go: -------------------------------------------------------------------------------- 1 | // Code generated by mockery v2.4.0-beta. DO NOT EDIT. 2 | 3 | package mocks 4 | 5 | import ( 6 | model "github.com/buidl-labs/Demux/model" 7 | mock "github.com/stretchr/testify/mock" 8 | ) 9 | 10 | // StorageDealDatabase is an autogenerated mock type for the StorageDealDatabase type 11 | type StorageDealDatabase struct { 12 | mock.Mock 13 | } 14 | 15 | // GetPendingDeals provides a mock function with given fields: 16 | func (_m *StorageDealDatabase) GetPendingDeals() ([]model.StorageDeal, error) { 17 | ret := _m.Called() 18 | 19 | var r0 []model.StorageDeal 20 | if rf, ok := ret.Get(0).(func() []model.StorageDeal); ok { 21 | r0 = rf() 22 | } else { 23 | if ret.Get(0) != nil { 24 | r0 = ret.Get(0).([]model.StorageDeal) 25 | } 26 | } 27 | 28 | var r1 error 29 | if rf, ok := ret.Get(1).(func() error); ok { 30 | r1 = rf() 31 | } else { 32 | r1 = ret.Error(1) 33 | } 34 | 35 | return r0, r1 36 | } 37 | 38 | // GetStorageDeal provides a mock function with given fields: _a0 39 | func (_m *StorageDealDatabase) GetStorageDeal(_a0 string) (model.StorageDeal, error) { 40 | ret := _m.Called(_a0) 41 | 42 | var r0 model.StorageDeal 43 | if rf, ok := ret.Get(0).(func(string) model.StorageDeal); ok { 44 | r0 = rf(_a0) 45 | } else { 46 | r0 = ret.Get(0).(model.StorageDeal) 47 | } 48 | 49 | var r1 error 50 | if rf, ok := ret.Get(1).(func(string) error); ok { 51 | r1 = rf(_a0) 52 | } else { 53 | r1 = ret.Error(1) 54 | } 55 | 56 | return r0, r1 57 | } 58 | 59 | // GetStorageDealByCID provides a mock function with given fields: _a0 60 | func (_m *StorageDealDatabase) GetStorageDealByCID(_a0 string) (model.StorageDeal, error) { 61 | ret := _m.Called(_a0) 62 | 63 | var r0 model.StorageDeal 64 | if rf, ok := ret.Get(0).(func(string) model.StorageDeal); ok { 65 | r0 = rf(_a0) 66 | } else { 67 | r0 = ret.Get(0).(model.StorageDeal) 68 | } 69 | 70 | var r1 error 71 | if rf, ok := ret.Get(1).(func(string) error); ok { 72 | r1 = rf(_a0) 73 | } else { 74 | r1 = ret.Error(1) 75 | } 76 | 77 | return r0, r1 78 | } 79 | 80 | // InsertStorageDeal provides a mock function with given fields: _a0 81 | func (_m *StorageDealDatabase) InsertStorageDeal(_a0 model.StorageDeal) error { 82 | ret := _m.Called(_a0) 83 | 84 | var r0 error 85 | if rf, ok := ret.Get(0).(func(model.StorageDeal) error); ok { 86 | r0 = rf(_a0) 87 | } else { 88 | r0 = ret.Error(0) 89 | } 90 | 91 | return r0 92 | } 93 | 94 | // UpdateStorageDeal provides a mock function with given fields: _a0, _a1, _a2, _a3, _a4, _a5 95 | func (_m *StorageDealDatabase) UpdateStorageDeal(_a0 string, _a1 uint32, _a2 string, _a3 string, _a4 string, _a5 int64) error { 96 | ret := _m.Called(_a0, _a1, _a2, _a3, _a4, _a5) 97 | 98 | var r0 error 99 | if rf, ok := ret.Get(0).(func(string, uint32, string, string, string, int64) error); ok { 100 | r0 = rf(_a0, _a1, _a2, _a3, _a4, _a5) 101 | } else { 102 | r0 = ret.Error(0) 103 | } 104 | 105 | return r0 106 | } 107 | -------------------------------------------------------------------------------- /dataservice/mocks/TranscodingDealDatabase.go: -------------------------------------------------------------------------------- 1 | // Code generated by mockery v2.4.0-beta. DO NOT EDIT. 2 | 3 | package mocks 4 | 5 | import ( 6 | model "github.com/buidl-labs/Demux/model" 7 | mock "github.com/stretchr/testify/mock" 8 | ) 9 | 10 | // TranscodingDealDatabase is an autogenerated mock type for the TranscodingDealDatabase type 11 | type TranscodingDealDatabase struct { 12 | mock.Mock 13 | } 14 | 15 | // GetTranscodingDeal provides a mock function with given fields: _a0 16 | func (_m *TranscodingDealDatabase) GetTranscodingDeal(_a0 string) (model.TranscodingDeal, error) { 17 | ret := _m.Called(_a0) 18 | 19 | var r0 model.TranscodingDeal 20 | if rf, ok := ret.Get(0).(func(string) model.TranscodingDeal); ok { 21 | r0 = rf(_a0) 22 | } else { 23 | r0 = ret.Get(0).(model.TranscodingDeal) 24 | } 25 | 26 | var r1 error 27 | if rf, ok := ret.Get(1).(func(string) error); ok { 28 | r1 = rf(_a0) 29 | } else { 30 | r1 = ret.Error(1) 31 | } 32 | 33 | return r0, r1 34 | } 35 | 36 | // InsertTranscodingDeal provides a mock function with given fields: _a0 37 | func (_m *TranscodingDealDatabase) InsertTranscodingDeal(_a0 model.TranscodingDeal) error { 38 | ret := _m.Called(_a0) 39 | 40 | var r0 error 41 | if rf, ok := ret.Get(0).(func(model.TranscodingDeal) error); ok { 42 | r0 = rf(_a0) 43 | } else { 44 | r0 = ret.Error(0) 45 | } 46 | 47 | return r0 48 | } 49 | -------------------------------------------------------------------------------- /dataservice/mocks/UploadDatabase.go: -------------------------------------------------------------------------------- 1 | // Code generated by mockery v2.4.0-beta. DO NOT EDIT. 2 | 3 | package mocks 4 | 5 | import ( 6 | model "github.com/buidl-labs/Demux/model" 7 | mock "github.com/stretchr/testify/mock" 8 | ) 9 | 10 | // UploadDatabase is an autogenerated mock type for the UploadDatabase type 11 | type UploadDatabase struct { 12 | mock.Mock 13 | } 14 | 15 | // GetUpload provides a mock function with given fields: _a0 16 | func (_m *UploadDatabase) GetUpload(_a0 string) (model.Upload, error) { 17 | ret := _m.Called(_a0) 18 | 19 | var r0 model.Upload 20 | if rf, ok := ret.Get(0).(func(string) model.Upload); ok { 21 | r0 = rf(_a0) 22 | } else { 23 | r0 = ret.Get(0).(model.Upload) 24 | } 25 | 26 | var r1 error 27 | if rf, ok := ret.Get(1).(func(string) error); ok { 28 | r1 = rf(_a0) 29 | } else { 30 | r1 = ret.Error(1) 31 | } 32 | 33 | return r0, r1 34 | } 35 | 36 | // IfUploadExists provides a mock function with given fields: _a0 37 | func (_m *UploadDatabase) IfUploadExists(_a0 string) bool { 38 | ret := _m.Called(_a0) 39 | 40 | var r0 bool 41 | if rf, ok := ret.Get(0).(func(string) bool); ok { 42 | r0 = rf(_a0) 43 | } else { 44 | r0 = ret.Get(0).(bool) 45 | } 46 | 47 | return r0 48 | } 49 | 50 | // InsertUpload provides a mock function with given fields: _a0 51 | func (_m *UploadDatabase) InsertUpload(_a0 model.Upload) error { 52 | ret := _m.Called(_a0) 53 | 54 | var r0 error 55 | if rf, ok := ret.Get(0).(func(model.Upload) error); ok { 56 | r0 = rf(_a0) 57 | } else { 58 | r0 = ret.Error(0) 59 | } 60 | 61 | return r0 62 | } 63 | 64 | // UpdateUploadStatus provides a mock function with given fields: _a0, _a1 65 | func (_m *UploadDatabase) UpdateUploadStatus(_a0 string, _a1 bool) error { 66 | ret := _m.Called(_a0, _a1) 67 | 68 | var r0 error 69 | if rf, ok := ret.Get(0).(func(string, bool) error); ok { 70 | r0 = rf(_a0, _a1) 71 | } else { 72 | r0 = ret.Error(0) 73 | } 74 | 75 | return r0 76 | } 77 | -------------------------------------------------------------------------------- /dataservice/mocks/UserDatabase.go: -------------------------------------------------------------------------------- 1 | // Code generated by mockery v2.4.0-beta. DO NOT EDIT. 2 | 3 | package mocks 4 | 5 | import mock "github.com/stretchr/testify/mock" 6 | 7 | // UserDatabase is an autogenerated mock type for the UserDatabase type 8 | type UserDatabase struct { 9 | mock.Mock 10 | } 11 | 12 | // IfUserExists provides a mock function with given fields: _a0 13 | func (_m *UserDatabase) IfUserExists(_a0 string) bool { 14 | ret := _m.Called(_a0) 15 | 16 | var r0 bool 17 | if rf, ok := ret.Get(0).(func(string) bool); ok { 18 | r0 = rf(_a0) 19 | } else { 20 | r0 = ret.Get(0).(bool) 21 | } 22 | 23 | return r0 24 | } 25 | 26 | // IncrementUserAssetCount provides a mock function with given fields: _a0 27 | func (_m *UserDatabase) IncrementUserAssetCount(_a0 string) error { 28 | ret := _m.Called(_a0) 29 | 30 | var r0 error 31 | if rf, ok := ret.Get(0).(func(string) error); ok { 32 | r0 = rf(_a0) 33 | } else { 34 | r0 = ret.Error(0) 35 | } 36 | 37 | return r0 38 | } 39 | -------------------------------------------------------------------------------- /dataservice/size_ratio.go: -------------------------------------------------------------------------------- 1 | package dataservice 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/buidl-labs/Demux/model" 7 | 8 | log "github.com/sirupsen/logrus" 9 | ) 10 | 11 | // SizeRatioDatabase provides the sizeRatio db operations. 12 | type SizeRatioDatabase interface { 13 | InsertSizeRatio(model.SizeRatio) error 14 | } 15 | 16 | type sizeRatioDatabase struct { 17 | db DatabaseHelper 18 | } 19 | 20 | // NewSizeRatioDatabase returns an instance of SizeRatioDatabase. 21 | func NewSizeRatioDatabase(db DatabaseHelper) SizeRatioDatabase { 22 | return &sizeRatioDatabase{ 23 | db: db, 24 | } 25 | } 26 | 27 | func (sr *sizeRatioDatabase) InsertSizeRatio(sizeRatio model.SizeRatio) error { 28 | insertResult, err := sr.db.Collection("sizeRatio").InsertOne(context.Background(), sizeRatio) 29 | if err != nil { 30 | log.Error("Inserting a sizeRatio:", err) 31 | return err 32 | } 33 | log.Info("Inserted a sizeRatio: ", insertResult) 34 | return nil 35 | } 36 | -------------------------------------------------------------------------------- /dataservice/storage_deal.go: -------------------------------------------------------------------------------- 1 | package dataservice 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/buidl-labs/Demux/model" 7 | 8 | log "github.com/sirupsen/logrus" 9 | 10 | "go.mongodb.org/mongo-driver/bson" 11 | "go.mongodb.org/mongo-driver/bson/primitive" 12 | ) 13 | 14 | // StorageDealDatabase provides the storageDeal db operations. 15 | type StorageDealDatabase interface { 16 | InsertStorageDeal(model.StorageDeal) error 17 | GetStorageDeal(string) (model.StorageDeal, error) 18 | GetStorageDealByCID(string) (model.StorageDeal, error) 19 | UpdateStorageDeal(string, uint32, string, string, string, int64) error 20 | GetPendingDeals() ([]model.StorageDeal, error) 21 | } 22 | 23 | type storageDealDatabase struct { 24 | db DatabaseHelper 25 | } 26 | 27 | // NewStorageDealDatabase returns an instance of StorageDealDatabase. 28 | func NewStorageDealDatabase(db DatabaseHelper) StorageDealDatabase { 29 | return &storageDealDatabase{ 30 | db: db, 31 | } 32 | } 33 | 34 | func (sd *storageDealDatabase) InsertStorageDeal(storageDeal model.StorageDeal) error { 35 | insertResult, err := sd.db.Collection("storageDeal").InsertOne(context.Background(), storageDeal) 36 | if err != nil { 37 | log.Error("Inserting a storageDeal:", err) 38 | return err 39 | } 40 | log.Info("Inserted a storageDeal: ", insertResult) 41 | return nil 42 | } 43 | 44 | func (sd *storageDealDatabase) GetStorageDeal(assetID string) (model.StorageDeal, error) { 45 | result := model.StorageDeal{} 46 | filter := bson.D{primitive.E{Key: "_id", Value: assetID}} 47 | err := sd.db.Collection("storageDeal").FindOne(context.Background(), filter).Decode(&result) 48 | if err != nil { 49 | log.Warn("Getting storageDeal: ", err) 50 | return result, err 51 | } 52 | log.Info("Getting storageDeal: ", result.AssetID) 53 | return result, nil 54 | } 55 | 56 | func (sd *storageDealDatabase) GetStorageDealByCID(CID string) (model.StorageDeal, error) { 57 | result := model.StorageDeal{} 58 | filter := bson.D{primitive.E{Key: "cid", Value: CID}} 59 | err := sd.db.Collection("storageDeal").FindOne(context.Background(), filter).Decode(&result) 60 | if err != nil { 61 | log.Warn("Getting storageDeal: ", err) 62 | return result, err 63 | } 64 | log.Info("Getting storageDeal: ", result.AssetID) 65 | return result, nil 66 | } 67 | 68 | func (sd *storageDealDatabase) UpdateStorageDeal(CID string, storageStatusCode uint32, storageStatus string, miner string, storageCost string, filecoinDealExpiry int64) error { 69 | filter := bson.M{"cid": CID} 70 | update := bson.M{"$set": bson.M{ 71 | "storage_status_code": storageStatusCode, 72 | "storage_status": storageStatus, 73 | "miner": miner, 74 | "storage_cost": storageCost, 75 | "filecoin_deal_expiry": filecoinDealExpiry, 76 | }} 77 | result, err := sd.db.Collection("storageDeal").UpdateOne(context.Background(), filter, update) 78 | if err != nil { 79 | log.Error("Updating storageDeal: ", err) 80 | return err 81 | } 82 | log.Info("Updating storageDeal: ", result) 83 | return nil 84 | } 85 | 86 | func (sd *storageDealDatabase) GetPendingDeals() ([]model.StorageDeal, error) { 87 | var results = []model.StorageDeal{} 88 | 89 | filter := bson.D{primitive.E{Key: "storage_status_code", Value: 0}} 90 | cur, err := sd.db.Collection("storageDeal").Find(context.Background(), filter) 91 | if err != nil { 92 | log.Error("Getting pending storage deals: ", err) 93 | return results, err 94 | } 95 | 96 | for cur.Next(context.Background()) { 97 | var result model.StorageDeal 98 | e := cur.Decode(&result) 99 | if e != nil { 100 | log.Error("Getting pending storage deals: ", e) 101 | return results, e 102 | } 103 | results = append(results, result) 104 | } 105 | if err := cur.Err(); err != nil { 106 | log.Error("Getting pending storage deals: ", err) 107 | return results, err 108 | } 109 | 110 | cur.Close(context.Background()) 111 | log.Info("Getting pending storage deals: ", len(results)) 112 | return results, nil 113 | } 114 | -------------------------------------------------------------------------------- /dataservice/transcoding_deal.go: -------------------------------------------------------------------------------- 1 | package dataservice 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/buidl-labs/Demux/model" 7 | 8 | log "github.com/sirupsen/logrus" 9 | 10 | "go.mongodb.org/mongo-driver/bson" 11 | "go.mongodb.org/mongo-driver/bson/primitive" 12 | ) 13 | 14 | // TranscodingDealDatabase provides the transcodingDeal db operations. 15 | type TranscodingDealDatabase interface { 16 | InsertTranscodingDeal(model.TranscodingDeal) error 17 | GetTranscodingDeal(string) (model.TranscodingDeal, error) 18 | } 19 | 20 | type transcodingDealDatabase struct { 21 | db DatabaseHelper 22 | } 23 | 24 | // NewTranscodingDealDatabase returns an instance of TranscodingDealDatabase. 25 | func NewTranscodingDealDatabase(db DatabaseHelper) TranscodingDealDatabase { 26 | return &transcodingDealDatabase{ 27 | db: db, 28 | } 29 | } 30 | 31 | func (t *transcodingDealDatabase) InsertTranscodingDeal(transcodingDeal model.TranscodingDeal) error { 32 | insertResult, err := t.db.Collection("transcodingDeal").InsertOne(context.Background(), transcodingDeal) 33 | if err != nil { 34 | log.Error("Inserting a transcodingDeal: ", err) 35 | return err 36 | } 37 | log.Info("Inserted a transcodingDeal: ", insertResult) 38 | return nil 39 | } 40 | 41 | func (t *transcodingDealDatabase) GetTranscodingDeal(assetID string) (model.TranscodingDeal, error) { 42 | result := model.TranscodingDeal{} 43 | filter := bson.D{primitive.E{Key: "_id", Value: assetID}} 44 | err := t.db.Collection("transcodingDeal").FindOne(context.Background(), filter).Decode(&result) 45 | if err != nil { 46 | log.Warn("Getting transcodingDeal: ", err) 47 | return result, err 48 | } 49 | log.Info("Getting transcodingDeal: ", result.AssetID) 50 | return result, nil 51 | } 52 | -------------------------------------------------------------------------------- /dataservice/upload.go: -------------------------------------------------------------------------------- 1 | package dataservice 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/buidl-labs/Demux/model" 7 | 8 | log "github.com/sirupsen/logrus" 9 | 10 | "go.mongodb.org/mongo-driver/bson" 11 | "go.mongodb.org/mongo-driver/bson/primitive" 12 | ) 13 | 14 | // UploadDatabase provides the upload db operations. 15 | type UploadDatabase interface { 16 | InsertUpload(model.Upload) error 17 | GetUpload(string) (model.Upload, error) 18 | IfUploadExists(string) bool 19 | UpdateUploadStatus(string, bool) error 20 | } 21 | 22 | type uploadDatabase struct { 23 | db DatabaseHelper 24 | } 25 | 26 | // NewUploadDatabase returns an instance of UploadDatabase. 27 | func NewUploadDatabase(db DatabaseHelper) UploadDatabase { 28 | return &uploadDatabase{ 29 | db: db, 30 | } 31 | } 32 | 33 | func (up *uploadDatabase) InsertUpload(upload model.Upload) error { 34 | insertResult, err := up.db.Collection("upload").InsertOne(context.Background(), upload) 35 | if err != nil { 36 | log.Error("Inserting an upload: ", err) 37 | return err 38 | } 39 | log.Info("Inserted an upload: ", insertResult) 40 | return nil 41 | } 42 | 43 | func (up *uploadDatabase) GetUpload(assetID string) (model.Upload, error) { 44 | result := model.Upload{} 45 | filter := bson.D{primitive.E{Key: "_id", Value: assetID}} 46 | err := up.db.Collection("upload").FindOne(context.Background(), filter).Decode(&result) 47 | if err != nil { 48 | log.Error("Getting upload: ", err) 49 | return result, err 50 | } 51 | log.Info("Getting upload: ", result.AssetID) 52 | return result, nil 53 | } 54 | 55 | func (up *uploadDatabase) IfUploadExists(assetID string) bool { 56 | result := model.Upload{} 57 | filter := bson.D{primitive.E{Key: "_id", Value: assetID}} 58 | err := up.db.Collection("upload").FindOne(context.Background(), filter).Decode(&result) 59 | if err != nil { 60 | log.Error("Checking if upload exists: ", err) 61 | return false 62 | } 63 | log.Info("Checking if upload exists: ", true) 64 | return true 65 | } 66 | 67 | func (up *uploadDatabase) UpdateUploadStatus(assetID string, status bool) error { 68 | filter := bson.M{"_id": assetID} 69 | update := bson.M{"$set": bson.M{ 70 | "status": status, 71 | }} 72 | result, err := up.db.Collection("upload").UpdateOne(context.Background(), filter, update) 73 | if err != nil { 74 | log.Error("Updating upload status: ", err) 75 | return err 76 | } 77 | log.Info("Updating upload status: ", result) 78 | return nil 79 | } 80 | -------------------------------------------------------------------------------- /dataservice/user.go: -------------------------------------------------------------------------------- 1 | package dataservice 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/buidl-labs/Demux/model" 7 | 8 | log "github.com/sirupsen/logrus" 9 | 10 | "go.mongodb.org/mongo-driver/bson" 11 | "go.mongodb.org/mongo-driver/bson/primitive" 12 | ) 13 | 14 | // UserDatabase provides the user db operations. 15 | type UserDatabase interface { 16 | IfUserExists(string) bool 17 | IncrementUserAssetCount(string) error 18 | } 19 | 20 | type userDatabase struct { 21 | db DatabaseHelper 22 | } 23 | 24 | // NewUserDatabase returns an instance of UserDatabase. 25 | func NewUserDatabase(db DatabaseHelper) UserDatabase { 26 | return &userDatabase{ 27 | db: db, 28 | } 29 | } 30 | 31 | func (u *userDatabase) IfUserExists(digest string) bool { 32 | result := model.User{} 33 | filter := bson.D{primitive.E{Key: "digest", Value: digest}} 34 | err := u.db.Collection("user").FindOne(context.Background(), filter).Decode(&result) 35 | if err != nil { 36 | log.Error("Checking if user exists: ", err) 37 | return false 38 | } 39 | log.Info("Checking if user exists: ", true) 40 | return true 41 | } 42 | 43 | // IncrementUserAssetCount increments a user's AssetCount by 1. 44 | func (u *userDatabase) IncrementUserAssetCount(digest string) error { 45 | result, err := u.db.Collection("user").UpdateOne(context.Background(), bson.M{ 46 | "digest": digest, 47 | }, bson.D{ 48 | primitive.E{Key: "$inc", Value: bson.D{primitive.E{Key: "asset_count", Value: 1}}}, 49 | }) 50 | if err != nil { 51 | log.Error("Incrementing user asset count: ", err) 52 | return err 53 | } 54 | log.Info("Incrementing user asset count: ", result) 55 | return nil 56 | } 57 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/buidl-labs/Demux 2 | 3 | go 1.15 4 | 5 | require ( 6 | github.com/google/uuid v1.2.0 7 | github.com/gorilla/mux v1.8.0 8 | github.com/ipfs/go-cid v0.0.7 9 | github.com/sirupsen/logrus v1.7.0 10 | github.com/stretchr/testify v1.7.0 11 | github.com/textileio/powergate/v2 v2.4.0 12 | go.mongodb.org/mongo-driver v1.4.2 13 | ) 14 | -------------------------------------------------------------------------------- /internal/internal.go: -------------------------------------------------------------------------------- 1 | package internal 2 | 3 | // AssetStatusMap maps asset_status_code with the corresponding asset_status. 4 | var AssetStatusMap = map[int32]string{ 5 | -1: "asset created", 6 | 0: "video uploaded successfully", 7 | 1: "processing in livepeer", 8 | 2: "attempting to pin to ipfs", 9 | 3: "pinned to ipfs, attempting to store in filecoin", 10 | 4: "stored in filecoin", 11 | } 12 | -------------------------------------------------------------------------------- /livepeerPull/configs/profiles.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "my-stream", 3 | "profiles": [ 4 | { 5 | "name": "1080p", 6 | "bitrate": 6000000, 7 | "fps": 30, 8 | "width": 1920, 9 | "height": 1080 10 | }, 11 | { 12 | "name": "720p", 13 | "bitrate": 2000000, 14 | "fps": 30, 15 | "width": 1280, 16 | "height": 720 17 | }, 18 | { 19 | "name": "360p", 20 | "bitrate": 500000, 21 | "fps": 30, 22 | "width": 640, 23 | "height": 360 24 | } 25 | ] 26 | } 27 | -------------------------------------------------------------------------------- /livepeerPull/darwin/place_mac_livepeer_bin_here: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/buidl-labs/Demux/dcf02bf6ed2e13b62c535cfadc708fbbba318d96/livepeerPull/darwin/place_mac_livepeer_bin_here -------------------------------------------------------------------------------- /livepeerPull/linux/place_linux_livepeer_bin_here: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/buidl-labs/Demux/dcf02bf6ed2e13b62c535cfadc708fbbba318d96/livepeerPull/linux/place_linux_livepeer_bin_here -------------------------------------------------------------------------------- /model/model.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | // Asset is the entity (video) which is uploaded by the user. 4 | type Asset struct { 5 | AssetID string `bson:"_id" json:"_id"` 6 | AssetReady bool `bson:"asset_ready" json:"asset_ready"` 7 | AssetStatusCode int32 `bson:"asset_status_code" json:"asset_status_code"` 8 | AssetStatus string `bson:"asset_status" json:"asset_status"` 9 | AssetError bool `bson:"asset_error" json:"asset_error"` 10 | StreamURL string `bson:"stream_url" json:"stream_url"` 11 | Thumbnail string `bson:"thumbnail" json:"thumbnail"` 12 | CreatedAt int64 `bson:"created_at" json:"created_at"` 13 | } 14 | 15 | // Upload is the entity (video) which is uploaded by the client. 16 | type Upload struct { 17 | AssetID string `bson:"_id" json:"_id"` 18 | URL string `bson:"url" json:"url"` 19 | Status bool `bson:"status" json:"status"` 20 | Error bool `bson:"error" json:"error"` 21 | } 22 | 23 | // TranscodingDeal is the type binding for a transcoding deal in the livepeer network. 24 | type TranscodingDeal struct { 25 | AssetID string `bson:"_id" json:"_id"` 26 | TranscodingCost string `bson:"transcoding_cost" json:"transcoding_cost"` 27 | TranscodingCostEstimated string `bson:"transcoding_cost_estimated" json:"transcoding_cost_estimated"` 28 | } 29 | 30 | // StorageDeal is the type binding for a storage deal in the IPFS/filecoin network. 31 | type StorageDeal struct { 32 | AssetID string `bson:"_id" json:"_id"` 33 | StorageStatusCode uint32 `bson:"storage_status_code" json:"storage_status_code"` 34 | StorageStatus string `bson:"storage_status" json:"storage_status"` 35 | CID string `bson:"cid" json:"cid"` 36 | Miner string `bson:"miner" json:"miner"` 37 | StorageCost string `bson:"storage_cost" json:"storage_cost"` 38 | StorageCostEstimated string `bson:"storage_cost_estimated" json:"storage_cost_estimated"` 39 | FilecoinDealExpiry int64 `bson:"filecoin_deal_expiry" json:"filecoin_deal_expiry"` 40 | FFSToken string `bson:"ffs_token" json:"ffs_token"` 41 | JobID string `bson:"job_id" json:"job_id"` 42 | } 43 | 44 | // User is the type binding for HTTP Basic Authentication. 45 | type User struct { 46 | Name string `bson:"name" json:"name"` 47 | TokenID string `bson:"token_id" json:"token_id"` 48 | Digest string `bson:"digest" json:"digest"` 49 | AssetCount uint64 `bson:"asset_count" json:"asset_count"` 50 | CreatedAt int64 `bson:"created_at" json:"created_at"` 51 | } 52 | 53 | // SizeRatio store the ratio StreamFolderSize/VideoFileSize. 54 | type SizeRatio struct { 55 | AssetID string `bson:"_id" json:"_id"` 56 | SizeRatio float64 `bson:"size_ratio" json:"size_ratio"` 57 | VideoFileSize uint64 `bson:"video_file_fize" json:"video_file_fize"` 58 | StreamFolderSize uint64 `bson:"stream_folder_size" json:"stream_folder_size"` 59 | } 60 | 61 | // MeanSizeRatio stores the mean SizeRatio of all assets. 62 | type MeanSizeRatio struct { 63 | ID int64 `bson:"_id" json:"_id"` 64 | MeanSizeRatio float64 `bson:"ratio" json:"ratio"` 65 | RatioSum float64 `bson:"ratio_sum" json:"ratio_sum"` 66 | Count uint64 `bson:"count" json:"count"` 67 | } 68 | -------------------------------------------------------------------------------- /server/routes/asset.go: -------------------------------------------------------------------------------- 1 | package routes 2 | 3 | import ( 4 | "crypto/sha256" 5 | "encoding/hex" 6 | "math/big" 7 | "net/http" 8 | "os" 9 | "os/exec" 10 | "time" 11 | 12 | "github.com/buidl-labs/Demux/dataservice" 13 | "github.com/buidl-labs/Demux/model" 14 | "github.com/buidl-labs/Demux/util" 15 | "github.com/google/uuid" 16 | "github.com/gorilla/mux" 17 | log "github.com/sirupsen/logrus" 18 | ) 19 | 20 | // AssetHandler enables checking the status of an asset in its demux lifecycle. 21 | func AssetHandler(w http.ResponseWriter, r *http.Request, u dataservice.UserDatabase, a dataservice.AssetDatabase, up dataservice.UploadDatabase) { 22 | w.Header().Set("Access-Control-Allow-Origin", "*") 23 | w.Header().Set("Access-Control-Allow-Headers", "*") 24 | 25 | if r.Method == "POST" { 26 | // Verify auth tokens 27 | tokenID, tokenSecret, ok := r.BasicAuth() 28 | 29 | if ok { 30 | sha256Digest := sha256.Sum256([]byte(tokenID + ":" + tokenSecret)) 31 | sha256DigestStr := hex.EncodeToString(sha256Digest[:]) 32 | 33 | if u.IfUserExists(sha256DigestStr) { 34 | log.Info("User auth successful") 35 | // Generate a new assetID. 36 | id := uuid.New() 37 | 38 | // Create asset directory. 39 | cmd := exec.Command("mkdir", "./assets/"+id.String()) 40 | stdout, err := cmd.Output() 41 | if err != nil { 42 | log.Error(err) 43 | w.WriteHeader(http.StatusFailedDependency) 44 | data := map[string]interface{}{ 45 | "error": "could not create asset", 46 | } 47 | util.WriteResponse(data, w) 48 | return 49 | } 50 | _ = stdout 51 | 52 | // Create a new asset. 53 | a.InsertAsset(model.Asset{ 54 | AssetID: id.String(), 55 | AssetReady: false, 56 | AssetStatusCode: 0, 57 | AssetStatus: "asset created", 58 | AssetError: false, 59 | CreatedAt: time.Now().Unix(), 60 | Thumbnail: "", 61 | }) 62 | 63 | // Create a new upload. 64 | up.InsertUpload(model.Upload{ 65 | AssetID: id.String(), 66 | URL: os.Getenv("DEMUX_URL") + "fileupload/" + id.String(), 67 | Status: false, 68 | Error: false, 69 | }) 70 | 71 | u.IncrementUserAssetCount(sha256DigestStr) 72 | 73 | w.WriteHeader(http.StatusOK) 74 | data := map[string]interface{}{ 75 | "asset_id": id.String(), 76 | "url": os.Getenv("DEMUX_URL") + "fileupload/" + id.String(), 77 | } 78 | util.WriteResponse(data, w) 79 | } else { 80 | w.WriteHeader(http.StatusUnauthorized) 81 | data := map[string]interface{}{ 82 | "error": "please use a valid TOKEN_ID and TOKEN_SECRET", 83 | } 84 | util.WriteResponse(data, w) 85 | return 86 | } 87 | } else { 88 | w.WriteHeader(http.StatusUnauthorized) 89 | data := map[string]interface{}{ 90 | "error": "please use a valid TOKEN_ID and TOKEN_SECRET", 91 | } 92 | util.WriteResponse(data, w) 93 | return 94 | } 95 | } 96 | } 97 | 98 | // AssetStatusHandler returns the asset details and status. 99 | func AssetStatusHandler(w http.ResponseWriter, r *http.Request, a dataservice.AssetDatabase, t dataservice.TranscodingDealDatabase, sd dataservice.StorageDealDatabase) { 100 | w.Header().Set("Content-Type", "application/json") 101 | w.Header().Set("Access-Control-Allow-Origin", "*") 102 | 103 | if r.Method == "GET" { 104 | // Collect path parameters 105 | vars := mux.Vars(r) 106 | 107 | if a.IfAssetExists(vars["asset_id"]) { 108 | asset, err := a.GetAsset(vars["asset_id"]) 109 | transcodingDeal, _ := t.GetTranscodingDeal(vars["asset_id"]) 110 | storageDeal, _ := sd.GetStorageDeal(vars["asset_id"]) 111 | 112 | if err != nil { 113 | w.WriteHeader(http.StatusNotFound) 114 | data := map[string]interface{}{ 115 | "asset_id": nil, 116 | "error": "no such asset", 117 | } 118 | util.WriteResponse(data, w) 119 | } else { 120 | w.WriteHeader(http.StatusOK) 121 | data := map[string]interface{}{ 122 | "asset_id": asset.AssetID, 123 | "asset_ready": asset.AssetReady, 124 | "asset_status_code": asset.AssetStatusCode, 125 | "asset_status": asset.AssetStatus, 126 | "asset_error": asset.AssetError, 127 | "stream_url": asset.StreamURL, 128 | "thumbnail": asset.Thumbnail, 129 | "created_at": asset.CreatedAt, 130 | } 131 | storageCostBigInt := new(big.Int) 132 | storageCostBigInt, ok := storageCostBigInt.SetString(storageDeal.StorageCost, 10) 133 | if !ok { 134 | data["storage_cost"] = big.NewInt(0) 135 | } else { 136 | data["storage_cost"] = storageCostBigInt 137 | } 138 | 139 | storageCostEstimatedBigInt := new(big.Int) 140 | storageCostEstimatedBigInt, ok = storageCostEstimatedBigInt.SetString(storageDeal.StorageCostEstimated, 10) 141 | if !ok { 142 | data["storage_cost_estimated"] = big.NewInt(0) 143 | } else { 144 | data["storage_cost_estimated"] = storageCostEstimatedBigInt 145 | } 146 | 147 | transcodingCostBigInt := new(big.Int) 148 | transcodingCostBigInt, ok = transcodingCostBigInt.SetString(transcodingDeal.TranscodingCost, 10) 149 | if !ok { 150 | data["transcoding_cost"] = big.NewInt(0) 151 | } else { 152 | data["transcoding_cost"] = transcodingCostBigInt 153 | } 154 | 155 | transcodingCostEstimatedBigInt := new(big.Int) 156 | transcodingCostEstimatedBigInt, ok = transcodingCostEstimatedBigInt.SetString(transcodingDeal.TranscodingCostEstimated, 10) 157 | if !ok { 158 | data["transcoding_cost_estimated"] = big.NewInt(0) 159 | } else { 160 | data["transcoding_cost_estimated"] = transcodingCostEstimatedBigInt 161 | } 162 | 163 | util.WriteResponse(data, w) 164 | } 165 | } else { 166 | w.WriteHeader(http.StatusNotFound) 167 | data := map[string]interface{}{ 168 | "asset_id": nil, 169 | "error": "no such asset", 170 | } 171 | util.WriteResponse(data, w) 172 | } 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /server/routes/pricing.go: -------------------------------------------------------------------------------- 1 | package routes 2 | 3 | import ( 4 | "encoding/json" 5 | "math/big" 6 | "net/http" 7 | 8 | "github.com/buidl-labs/Demux/dataservice" 9 | "github.com/buidl-labs/Demux/util" 10 | 11 | log "github.com/sirupsen/logrus" 12 | ) 13 | 14 | // VideoData contains some data which is used to predict the streaming cost. 15 | type VideoData struct { 16 | StorageDuration int64 `json:"storage_duration"` 17 | VideoFileSize int64 `json:"video_file_size"` 18 | VideoDuration int64 `json:"video_duration"` 19 | } 20 | 21 | // PriceEstimateHandler handles the /pricing endpoint 22 | func PriceEstimateHandler(w http.ResponseWriter, r *http.Request, msr dataservice.MeanSizeRatioDatabase) { 23 | w.Header().Set("Access-Control-Allow-Origin", "*") 24 | w.Header().Set("Access-Control-Allow-Headers", "Content-Type") 25 | 26 | if r.Method == "POST" { 27 | var responded = false 28 | 29 | decoder := json.NewDecoder(r.Body) 30 | var d VideoData 31 | err := decoder.Decode(&d) 32 | if err != nil { 33 | w.WriteHeader(http.StatusInternalServerError) 34 | data := map[string]interface{}{ 35 | "error": "please specify a value of `storage_duration` between 2628003 and 315360000", 36 | } 37 | util.WriteResponse(data, w) 38 | log.Errorln(err) 39 | responded = true 40 | return 41 | } 42 | 43 | if d.StorageDuration > 315360000 || d.StorageDuration < 2628003 { 44 | w.WriteHeader(http.StatusExpectationFailed) 45 | data := map[string]interface{}{ 46 | "error": "please specify a value of `storage_duration` between 2628003 and 315360000", 47 | } 48 | util.WriteResponse(data, w) 49 | responded = true 50 | return 51 | } 52 | if d.VideoDuration < 1 { 53 | w.WriteHeader(http.StatusExpectationFailed) 54 | data := map[string]interface{}{ 55 | "error": "please specify a value of `video_duration` >= 1", 56 | } 57 | util.WriteResponse(data, w) 58 | responded = true 59 | return 60 | } 61 | if d.VideoFileSize <= 0 { 62 | w.WriteHeader(http.StatusExpectationFailed) 63 | data := map[string]interface{}{ 64 | "error": "please specify a value of `video_file_size` > 0", 65 | } 66 | util.WriteResponse(data, w) 67 | responded = true 68 | return 69 | } 70 | 71 | videoDurationInt := d.VideoDuration 72 | storageDurationInt := d.StorageDuration 73 | videoFileSize := uint64(d.VideoFileSize) 74 | 75 | transcodingCostWEI := big.NewInt(0) 76 | transcodingCostWEI, err = util.CalculateTranscodingCost("", float64(videoDurationInt)) 77 | if err != nil { 78 | log.Warn("Couldn't calculate transcoding cost: ", err) 79 | // Couldn't calculate transcoding cost. Let it be 0. 80 | } 81 | 82 | // Calculate powergate (filecoin) storage price 83 | 84 | storageCostEstimated := big.NewInt(0) 85 | 86 | duration := float64(storageDurationInt) // duration of deal in seconds (provided by user) 87 | epochs := float64(duration / float64(30)) 88 | folderSize, err := GetFolderSizeEstimate(float64(videoFileSize), msr) // size of folder in MiB (to be predicted by estimation algorithm) 89 | if err != nil { 90 | w.WriteHeader(http.StatusExpectationFailed) 91 | data := map[string]interface{}{ 92 | "error": "estimating folder size", 93 | } 94 | util.WriteResponse(data, w) 95 | responded = true 96 | return 97 | } 98 | log.Info("folderSize", folderSize, "videoFileSize", videoFileSize) 99 | log.Info("duration", duration, "epochs", epochs) 100 | 101 | // Calculate storage cost of the video 102 | storageCostEstimated, err = util.CalculateStorageCost(uint64(folderSize), int64(duration)) 103 | if err != nil { 104 | log.Warn("Couldn't calculate storage cost: ", err) 105 | // Couldn't calculate storage cost. Let it be 0. 106 | } 107 | 108 | // TODO: Convert total price to USD and return 109 | 110 | if responded == false { 111 | w.WriteHeader(http.StatusOK) 112 | data := map[string]interface{}{ 113 | "transcoding_cost_estimated": transcodingCostWEI, 114 | "storage_cost_estimated": storageCostEstimated, 115 | } 116 | util.WriteResponse(data, w) 117 | } 118 | } 119 | } 120 | 121 | // GetFolderSizeEstimate estimates the folderSize 122 | // (after transcoding) of an mp4 video using the meanSizeRatio. 123 | func GetFolderSizeEstimate(fileSize float64, msr dataservice.MeanSizeRatioDatabase) (float64, error) { 124 | msrObj, err := msr.GetMeanSizeRatio() 125 | 126 | return fileSize * float64(msrObj.MeanSizeRatio), err 127 | } 128 | -------------------------------------------------------------------------------- /server/routes/pricing_test.go: -------------------------------------------------------------------------------- 1 | package routes 2 | 3 | -------------------------------------------------------------------------------- /server/routes/upload.go: -------------------------------------------------------------------------------- 1 | package routes 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "context" 7 | "fmt" 8 | "io" 9 | "io/ioutil" 10 | "math" 11 | "math/big" 12 | "net/http" 13 | "os" 14 | "os/exec" 15 | "path/filepath" 16 | "runtime" 17 | "strconv" 18 | "strings" 19 | "sync" 20 | "time" 21 | 22 | log "github.com/sirupsen/logrus" 23 | 24 | "github.com/buidl-labs/Demux/dataservice" 25 | "github.com/buidl-labs/Demux/internal" 26 | "github.com/buidl-labs/Demux/model" 27 | "github.com/buidl-labs/Demux/util" 28 | "github.com/gorilla/mux" 29 | // "github.com/ipfs/go-cid" 30 | ) 31 | 32 | var maxFileSize = 30 * 1024 * 1024 33 | 34 | // FileUploadHandler handles the asset uploads using resumable.js 35 | func FileUploadHandler(w http.ResponseWriter, r *http.Request, a dataservice.AssetDatabase, up dataservice.UploadDatabase, t dataservice.TranscodingDealDatabase, sd dataservice.StorageDealDatabase, sr dataservice.SizeRatioDatabase, msr dataservice.MeanSizeRatioDatabase) { 36 | w.Header().Set("Access-Control-Allow-Origin", "*") 37 | w.Header().Set("Access-Control-Allow-Headers", "*") 38 | w.Header().Set("Access-Control-Allow-Methods", "*") 39 | 40 | if r.Method == "GET" { 41 | vars := mux.Vars(r) 42 | assetID := vars["asset_id"] 43 | 44 | if _, err := os.Stat("./assets/" + assetID); os.IsNotExist(err) { 45 | return 46 | } 47 | 48 | tempFolder := "./assets/" + assetID 49 | 50 | resumableIdentifier, _ := r.URL.Query()["resumableIdentifier"] 51 | resumableChunkNumber, _ := r.URL.Query()["resumableChunkNumber"] 52 | path := fmt.Sprintf("%s/%s", tempFolder, resumableIdentifier[0]) 53 | relativeChunk := fmt.Sprintf("%s%s%s%s", path, "/", "part", resumableChunkNumber[0]) 54 | 55 | if _, err := os.Stat(path); os.IsNotExist(err) { 56 | os.Mkdir(path, os.ModePerm) 57 | } 58 | 59 | if _, err := os.Stat(relativeChunk); os.IsNotExist(err) { 60 | http.Error(w, http.StatusText(http.StatusNotFound), http.StatusMethodNotAllowed) 61 | } else { 62 | http.Error(w, "Chunk already exist", http.StatusCreated) 63 | } 64 | } else if r.Method == "POST" { 65 | uploaded := false 66 | 67 | var videoFileSize int64 68 | 69 | vars := mux.Vars(r) 70 | assetID := vars["asset_id"] 71 | if !a.IfAssetExists(assetID) { 72 | // Set AssetError to true 73 | a.UpdateAssetStatus(assetID, -1, internal.AssetStatusMap[-1], true) 74 | log.Error("asset not found") 75 | return 76 | } 77 | 78 | if _, err := os.Stat("./assets/" + assetID); os.IsNotExist(err) { 79 | // Set AssetError to true 80 | a.UpdateAssetStatus(assetID, -1, internal.AssetStatusMap[-1], true) 81 | log.Error("asset doesn't exist:", err) 82 | return 83 | } 84 | 85 | tempFolder := "./assets/" + assetID 86 | 87 | file, _, err := r.FormFile("file") 88 | if err != nil { 89 | a.UpdateAssetStatus(assetID, -1, internal.AssetStatusMap[-1], true) 90 | log.Error(err) 91 | return 92 | } 93 | defer file.Close() 94 | 95 | resumableIdentifier, _ := r.URL.Query()["resumableIdentifier"] 96 | resumableChunkNumber, _ := r.URL.Query()["resumableChunkNumber"] 97 | resumableTotalChunks, _ := r.URL.Query()["resumableTotalChunks"] 98 | 99 | path := fmt.Sprintf("%s/%s", tempFolder, resumableIdentifier[0]) 100 | 101 | relativeChunk := fmt.Sprintf("%s%s%s%s", path, "/", "part", resumableChunkNumber[0]) 102 | 103 | if _, err := os.Stat(path); os.IsNotExist(err) { 104 | os.Mkdir(path, os.ModePerm) 105 | } 106 | 107 | f, err := os.OpenFile(relativeChunk, os.O_WRONLY|os.O_CREATE, 0666) 108 | if err != nil { 109 | a.UpdateAssetStatus(assetID, -1, internal.AssetStatusMap[-1], true) 110 | log.Error(err) 111 | return 112 | } 113 | defer f.Close() 114 | io.Copy(f, file) 115 | 116 | currentChunk, err := strconv.Atoi(resumableChunkNumber[0]) 117 | totalChunks, err := strconv.Atoi(resumableTotalChunks[0]) 118 | 119 | // If it is the last chunk, trigger the recombination of chunks 120 | if currentChunk == totalChunks { 121 | log.Info("Combining chunks into one file") 122 | resumableTotalSize, _ := r.URL.Query()["resumableTotalSize"] 123 | videoFileSizeInt, _ := strconv.Atoi(resumableTotalSize[0]) 124 | 125 | if videoFileSizeInt > maxFileSize { 126 | a.UpdateAssetStatus(assetID, -1, internal.AssetStatusMap[-1], true) 127 | log.Warn("Maximum file size is 30 MiB") 128 | return 129 | } 130 | videoFileSize = int64(videoFileSizeInt) 131 | 132 | chunkSizeInBytesStr, _ := r.URL.Query()["resumableChunkSize"] 133 | chunkSizeInBytes, _ := strconv.Atoi(chunkSizeInBytesStr[0]) 134 | 135 | chunksDir := path 136 | 137 | // Generate an empty file 138 | f, err := os.Create("./assets/" + assetID + "/testfile.mp4") 139 | if err != nil { 140 | a.UpdateAssetStatus(assetID, -1, internal.AssetStatusMap[-1], true) 141 | log.Error("couldn't create file from chunks", err) 142 | return 143 | } 144 | defer f.Close() 145 | 146 | // For every chunk, write it to the empty file. 147 | 148 | for i := 1; i <= totalChunks; i++ { 149 | relativePath := fmt.Sprintf("%s%s%d", chunksDir, "/part", i) 150 | 151 | writeOffset := int64(chunkSizeInBytes * (i - 1)) 152 | if i == 1 { 153 | writeOffset = 0 154 | } 155 | dat, err := ioutil.ReadFile(relativePath) 156 | size, err := f.WriteAt(dat, writeOffset) 157 | if err != nil { 158 | // Set AssetError true 159 | a.UpdateAssetStatus(assetID, -1, internal.AssetStatusMap[-1], true) 160 | log.Error("couldn't create file from chunks", err) 161 | return 162 | } 163 | log.Infof("%d bytes written offset %d\n", size, writeOffset) 164 | } 165 | 166 | uploaded = true 167 | up.UpdateUploadStatus(assetID, true) 168 | a.UpdateAssetStatus(assetID, 0, internal.AssetStatusMap[0], false) 169 | 170 | // Delete the temporary chunks 171 | exec.Command("rm", "-rf", tempFolder+"/"+resumableIdentifier[0]).Output() 172 | } else { 173 | log.Infof("currentChunk: %d, totalChunks: %d\n", currentChunk, totalChunks) 174 | } 175 | 176 | demuxFileName := "./assets/" + assetID + "/testfile.mp4" 177 | 178 | if uploaded { 179 | go func() { 180 | 181 | // Set AssetStatus to 1 (processing in livepeer) 182 | a.UpdateAssetStatus(assetID, 1, internal.AssetStatusMap[1], false) 183 | 184 | if err := Transcode(assetID, demuxFileName, videoFileSize); err != nil { 185 | log.Error(err) 186 | // Set AssetError to true 187 | a.UpdateAssetStatus(assetID, 1, internal.AssetStatusMap[1], true) 188 | return 189 | } 190 | 191 | // Calculate transcoding cost of the video. 192 | transcodingCostEstimated := big.NewInt(0) 193 | transcodingCostEstimated, err = util.CalculateTranscodingCost(demuxFileName, float64(0)) 194 | if err != nil { 195 | log.Warn("Couldn't calculate transcoding cost: ", err) 196 | // Couldn't calculate transcoding cost. Let it be 0. 197 | } 198 | 199 | if err := CreateStream(assetID, demuxFileName); err != nil { 200 | log.Error(err) 201 | // Set AssetError to true 202 | a.UpdateAssetStatus(assetID, 1, internal.AssetStatusMap[1], true) 203 | return 204 | } 205 | 206 | t.InsertTranscodingDeal(model.TranscodingDeal{ 207 | AssetID: assetID, 208 | TranscodingCost: big.NewInt(0).String(), 209 | TranscodingCostEstimated: transcodingCostEstimated.String(), 210 | }) 211 | 212 | // Set AssetStatus to 2 (attempting to pin to ipfs) 213 | a.UpdateAssetStatus(assetID, 2, internal.AssetStatusMap[2], false) 214 | 215 | // Set storageCostEstimated to 0. 216 | storageCostEstimated := big.NewInt(0) 217 | 218 | dirsize, err := util.DirSize("./assets/" + assetID) 219 | if err != nil { 220 | // dataservice.UpdateAssetStatus(assetID, 2, internal.AssetStatusMap[2], true) 221 | log.Warn("finding dirsize: ", err) 222 | } else { 223 | // Update sizeRatio 224 | _, _, _, _, err = UpdateSizeRatio(assetID, videoFileSize, dirsize, sr, msr) 225 | if err != nil { 226 | log.Warn("Couldn't process folder") 227 | } 228 | // Calculate storage cost of the video 229 | storageCostEstimated, err = util.CalculateStorageCost(dirsize, 31536000) 230 | if err != nil { 231 | log.Warn("Couldn't calculate storage cost: ", err) 232 | // Couldn't calculate storage cost. Let it be 0. 233 | } 234 | } 235 | 236 | ctx := context.Background() 237 | 238 | var currCID string 239 | var streamURL string 240 | var ipfsGateway = os.Getenv("IPFS_GATEWAY") 241 | var jid string 242 | var currFolderName string 243 | currCID, currFolderName, minerName, tok, jid, storagePrice, expiry, staged, err := util.RunPow(ctx, util.InitialPowergateSetup, "./assets/"+assetID) 244 | _ = minerName 245 | _ = storagePrice 246 | _ = expiry 247 | if err != nil { 248 | if staged { 249 | log.Warn(err) 250 | currCIDStr := fmt.Sprintf("%s", currCID) 251 | streamURL = ipfsGateway + currCIDStr + "/root.m3u8" 252 | 253 | log.Infof("CID: %s, currFolderName: %s\n", currCIDStr, currFolderName) 254 | 255 | sd.InsertStorageDeal(model.StorageDeal{ 256 | AssetID: assetID, 257 | StorageStatusCode: 0, 258 | StorageStatus: internal.AssetStatusMap[3], 259 | CID: currCIDStr, 260 | Miner: "", 261 | StorageCost: big.NewInt(0).String(), 262 | StorageCostEstimated: storageCostEstimated.String(), 263 | FilecoinDealExpiry: int64(0), 264 | FFSToken: tok, 265 | JobID: jid, 266 | }) 267 | 268 | // Update streamURL of the asset 269 | a.UpdateStreamURL(assetID, streamURL) 270 | 271 | // Update thumbnail of the asset 272 | a.UpdateThumbnail(assetID, ipfsGateway+currCIDStr+"/thumbnail.png") 273 | 274 | // Set AssetStatus to 3 (pinned to ipfs, attempting to store in filecoin) 275 | a.UpdateAssetStatus(assetID, 3, internal.AssetStatusMap[3], false) 276 | } else { 277 | // Set AssetError to true 278 | a.UpdateAssetStatus(assetID, 2, internal.AssetStatusMap[2], true) 279 | log.Error(err) 280 | } 281 | return 282 | } 283 | 284 | currCIDStr := fmt.Sprintf("%s", currCID) 285 | streamURL = ipfsGateway + currCIDStr + "/root.m3u8" 286 | 287 | log.Infof("CID: %s, currFolderName: %s\n", currCIDStr, currFolderName) 288 | 289 | sd.InsertStorageDeal(model.StorageDeal{ 290 | AssetID: assetID, 291 | StorageStatusCode: 0, 292 | StorageStatus: internal.AssetStatusMap[3], 293 | CID: currCIDStr, 294 | Miner: "", 295 | StorageCost: big.NewInt(0).String(), 296 | StorageCostEstimated: storageCostEstimated.String(), 297 | FilecoinDealExpiry: int64(0), 298 | FFSToken: tok, 299 | JobID: jid, 300 | }) 301 | 302 | // Update streamURL of the asset 303 | a.UpdateStreamURL(assetID, streamURL) 304 | 305 | // Update thumbnail of the asset 306 | a.UpdateThumbnail(assetID, ipfsGateway+currCIDStr+"/thumbnail.png") 307 | 308 | // Set AssetStatus to 3 (pinned to ipfs, attempting to store in filecoin) 309 | a.UpdateAssetStatus(assetID, 3, internal.AssetStatusMap[3], false) 310 | 311 | // Set AssetReady to true 312 | a.UpdateAssetReady(assetID, true) 313 | }() 314 | 315 | w.WriteHeader(http.StatusOK) 316 | data := map[string]interface{}{ 317 | "asset_id": assetID, 318 | } 319 | util.WriteResponse(data, w) 320 | } 321 | } 322 | } 323 | 324 | // UploadStatusHandler returns the upload details and status. 325 | func UploadStatusHandler(w http.ResponseWriter, r *http.Request, up dataservice.UploadDatabase) { 326 | w.Header().Set("Content-Type", "application/json") 327 | if r.Method == "GET" { 328 | vars := mux.Vars(r) 329 | 330 | unknownStatusData := map[string]interface{}{ 331 | "asset_id": vars["asset_id"], 332 | "status": false, 333 | "error": false, 334 | "url": "", 335 | } 336 | 337 | if up.IfUploadExists(vars["asset_id"]) { 338 | upload, err := up.GetUpload(vars["asset_id"]) 339 | if err != nil { 340 | w.WriteHeader(http.StatusNotFound) 341 | util.WriteResponse(unknownStatusData, w) 342 | } 343 | w.WriteHeader(http.StatusOK) 344 | data := map[string]interface{}{ 345 | "asset_id": upload.AssetID, 346 | "status": upload.Status, 347 | "error": upload.Error, 348 | "url": upload.URL, 349 | } 350 | util.WriteResponse(data, w) 351 | } else { 352 | w.WriteHeader(http.StatusNotFound) 353 | util.WriteResponse(unknownStatusData, w) 354 | } 355 | } 356 | } 357 | 358 | // Transcode transcodes the video in the livepeer network. 359 | func Transcode(assetID string, demuxFileName string, videoFileSize int64) error { 360 | livepeerPullCompleted := false 361 | 362 | livepeerAPIKey, livepeerAPIKeyExists := os.LookupEnv("LIVEPEER_COM_API_KEY") 363 | if !livepeerAPIKeyExists { 364 | return fmt.Errorf("please provide the environment variable `LIVEPEER_COM_API_KEY`") 365 | } 366 | 367 | log.Info("Starting livepeer transcoding") 368 | 369 | goos := runtime.GOOS 370 | lpCmd := exec.Command("./livepeerPull/"+goos+"/livepeer", "-pull", demuxFileName, 371 | "-recordingDir", "./assets/"+assetID, "-transcodingOptions", 372 | "./livepeerPull/configs/profiles.json", "-apiKey", 373 | livepeerAPIKey, "-v", "99", "-mediaDir", "./assets/"+assetID) 374 | 375 | var buf bytes.Buffer 376 | lpCmd.Stdout = &buf 377 | 378 | lpCmd.Start() 379 | 380 | done := make(chan error) 381 | go func() { done <- lpCmd.Wait() }() 382 | 383 | var timeout <-chan time.Time 384 | var limit int64 = int64(maxFileSize) 385 | 386 | if videoFileSize <= limit/4 { 387 | timeout = time.After(2 * time.Minute) 388 | } else if videoFileSize <= limit/2 { 389 | timeout = time.After(3 * time.Minute) 390 | } else if videoFileSize <= limit*3/4 { 391 | timeout = time.After(4 * time.Minute) 392 | } else { 393 | timeout = time.After(5 * time.Minute) 394 | } 395 | 396 | select { 397 | case <-timeout: 398 | lpCmd.Process.Kill() 399 | return fmt.Errorf("livepeer pull timed out") 400 | case err := <-done: 401 | if err != nil { 402 | return fmt.Errorf("livepeer transcoding unsuccessful") 403 | } 404 | livepeerPullCompleted = true 405 | log.Info("Completed livepeer transcoding") 406 | } 407 | 408 | // Return error if livepeer pull fails or times out 409 | if livepeerPullCompleted == false { 410 | return fmt.Errorf("livepeer transcoding unsuccessful") 411 | } 412 | return nil 413 | } 414 | 415 | // CreateStream generates the m3u8 files. 416 | func CreateStream(assetID string, demuxFileName string) error { 417 | items, err := ioutil.ReadDir("./assets/" + assetID) 418 | if err != nil { 419 | return err 420 | } 421 | 422 | for _, f := range items { 423 | if f.IsDir() { 424 | resos := [4]string{"source", "1080p", "720p", "360p"} 425 | 426 | var pWg sync.WaitGroup 427 | pWg.Add(4) 428 | 429 | for _, res := range resos { 430 | go func(res string) { 431 | segments, err := ioutil.ReadDir("./assets/" + assetID + "/" + f.Name() + "/" + res) 432 | if err != nil { 433 | return 434 | } 435 | 436 | durations := make([]string, len(segments)) 437 | durSum := float64(0) 438 | 439 | for i, seg := range segments { 440 | segName := seg.Name() 441 | 442 | stdout, err := exec.Command("ffprobe", "-i", "./assets/"+assetID+"/"+f.Name()+"/"+res+"/"+segName, "-show_entries", "format=duration", "-v", "quiet", "-of", "csv=p=0").Output() 443 | if err != nil { 444 | return 445 | } 446 | duration, err := strconv.ParseFloat(string(stdout)[:len(string(stdout))-2], 64) 447 | if err != nil { 448 | return 449 | } 450 | 451 | durSum += duration 452 | durations[i] = fmt.Sprintf("%.3f", duration) 453 | } 454 | 455 | var m3u8str strings.Builder 456 | m3u8str.WriteString("#EXTM3U\n" + 457 | "#EXT-X-VERSION:3\n" + 458 | "#EXT-X-TARGETDURATION:" + strconv.Itoa(int(durSum)) + "\n" + 459 | "#EXT-X-MEDIA-SEQUENCE:0\n") 460 | for i, dur := range durations { 461 | m3u8str.WriteString("#EXTINF:" + dur + ",\n" + 462 | res + "/" + strconv.Itoa(i) + ".ts\n") 463 | } 464 | m3u8str.WriteString("#EXT-X-ENDLIST\n") 465 | 466 | m3u8strFile, err := os.Create("./assets/" + assetID + "/" + f.Name() + "/" + res + ".m3u8") 467 | bWriter := bufio.NewWriter(m3u8strFile) 468 | n, err := bWriter.WriteString(m3u8str.String()) 469 | if err != nil { 470 | return 471 | } 472 | _ = n 473 | bWriter.Flush() 474 | 475 | pWg.Done() 476 | }(res) 477 | } 478 | pWg.Wait() 479 | } 480 | } 481 | 482 | // generate thumbnail 483 | exec.Command("ffmpeg", "-i", demuxFileName, "-ss", "00:00:01.000", "-vframes", "1", "./assets/"+assetID+"/thumbnail.png").Output() 484 | 485 | rmcmd := exec.Command("rm", "-rf", demuxFileName) 486 | _, err = rmcmd.Output() 487 | if err != nil { 488 | return err 489 | } 490 | 491 | pattern := "./assets/" + assetID + "/*.mp4" 492 | matches, err := filepath.Glob(pattern) 493 | if err != nil { 494 | return err 495 | } 496 | 497 | for _, match := range matches { 498 | rmcmd = exec.Command("rm", "-rf", match) 499 | _, err = rmcmd.Output() 500 | if err != nil { 501 | return err 502 | } 503 | } 504 | 505 | pattern = "./assets/" + assetID + "/*.m3u8" 506 | matches, err = filepath.Glob(pattern) 507 | if err != nil { 508 | return err 509 | } 510 | if len(matches) == 1 { 511 | renameCmd := exec.Command("cp", matches[0], "./assets/"+assetID+"/root.m3u8") 512 | stdout, err := renameCmd.Output() 513 | if err != nil { 514 | return err 515 | } 516 | _ = stdout 517 | } 518 | 519 | return nil 520 | } 521 | 522 | // UpdateSizeRatio updates the sizeRatioCollection with the 523 | // current asset file and folder size details. 524 | func UpdateSizeRatio(assetID string, videoFileSize int64, dirsize uint64, sr dataservice.SizeRatioDatabase, msr dataservice.MeanSizeRatioDatabase) (uint64, float64, float64, float64, error) { 525 | dirsize = dirsize / (1024 * 1024) 526 | videoFileSize = videoFileSize / (1024 * 1024) 527 | ratio := float64(dirsize) / float64(videoFileSize) 528 | ratio = math.Round(ratio*100) / 100 529 | 530 | msrObj, err := msr.GetMeanSizeRatio() 531 | if err != nil { 532 | log.Error("getting msr:", err) 533 | return dirsize, ratio, msrObj.MeanSizeRatio, msrObj.MeanSizeRatio, err 534 | } 535 | 536 | if uint64(videoFileSize) == 0 || ratio == 0 || dirsize == 0 || ratio == math.Inf(1) { 537 | log.Errorf("unexpected value. videoFileSize: %d, dirsize: %d\n", videoFileSize, dirsize) 538 | return dirsize, ratio, msrObj.MeanSizeRatio, msrObj.MeanSizeRatio, fmt.Errorf("unexpected size") 539 | } 540 | sr.InsertSizeRatio(model.SizeRatio{ 541 | AssetID: assetID, 542 | SizeRatio: ratio, 543 | VideoFileSize: uint64(videoFileSize), 544 | StreamFolderSize: dirsize, 545 | }) 546 | 547 | currRatioSum := math.Round(msrObj.RatioSum*100) / 100 548 | currCount := msrObj.Count 549 | updatedMsr := math.Round(((ratio+currRatioSum)/float64(currCount+1))*100) / 100 550 | msr.UpdateMeanSizeRatio(updatedMsr, ratio+currRatioSum, currCount+1) 551 | 552 | return dirsize, ratio, msrObj.MeanSizeRatio, updatedMsr, nil 553 | } 554 | -------------------------------------------------------------------------------- /server/routes/upload_test.go: -------------------------------------------------------------------------------- 1 | package routes 2 | 3 | import "testing" 4 | 5 | func TestTranscode(t *testing.T) { 6 | if 1 == 1 { 7 | t.Log("gr8 job transcoding") 8 | } 9 | } 10 | 11 | func TestCreateStream(t *testing.T) { 12 | if 1 == 1 { 13 | t.Log("gr8 job") 14 | } 15 | } 16 | func TestUpdateSizeRatio(t *testing.T) { 17 | // dirsize, ratio, msr, updatedMsr, err:=UpdateSizeRatio("f14d165a-094e-4d8d-a01f-30fcefbc6ddd", int64(21*1024*1024), uint64(46*1024*1024)) 18 | if 1 == 2 { 19 | t.Error("one is not equal to two") 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /server/server.go: -------------------------------------------------------------------------------- 1 | package server 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | 7 | "github.com/buidl-labs/Demux/dataservice" 8 | "github.com/buidl-labs/Demux/server/routes" 9 | 10 | "github.com/gorilla/mux" 11 | log "github.com/sirupsen/logrus" 12 | ) 13 | 14 | // HomeHandler handles the home route 15 | func HomeHandler(w http.ResponseWriter, r *http.Request) { 16 | w.WriteHeader(http.StatusOK) 17 | fmt.Fprintln(w, "Hello, world!") 18 | } 19 | 20 | // StartServer starts the web server 21 | func StartServer(serverPort string, db dataservice.DatabaseHelper) { 22 | assetDB := dataservice.NewAssetDatabase(db) 23 | uploadDB := dataservice.NewUploadDatabase(db) 24 | transcodingDealDB := dataservice.NewTranscodingDealDatabase(db) 25 | storageDealDB := dataservice.NewStorageDealDatabase(db) 26 | userDB := dataservice.NewUserDatabase(db) 27 | sizeRatioDB := dataservice.NewSizeRatioDatabase(db) 28 | meanSizeRatioDB := dataservice.NewMeanSizeRatioDatabase(db) 29 | 30 | router := mux.NewRouter() 31 | 32 | router.HandleFunc("/", HomeHandler).Methods("GET", http.MethodOptions) 33 | router.HandleFunc("/asset", func(w http.ResponseWriter, r *http.Request) { 34 | routes.AssetHandler(w, r, userDB, assetDB, uploadDB) 35 | }).Methods("POST", http.MethodOptions) 36 | router.HandleFunc("/asset/{asset_id}", func(w http.ResponseWriter, r *http.Request) { 37 | routes.AssetStatusHandler(w, r, assetDB, transcodingDealDB, storageDealDB) 38 | }).Methods("GET", http.MethodOptions) 39 | router.HandleFunc("/pricing", func(w http.ResponseWriter, r *http.Request) { 40 | routes.PriceEstimateHandler(w, r, meanSizeRatioDB) 41 | }).Methods("POST", http.MethodOptions) 42 | router.HandleFunc("/fileupload/{asset_id}", func(w http.ResponseWriter, r *http.Request) { 43 | routes.FileUploadHandler(w, r, assetDB, uploadDB, transcodingDealDB, storageDealDB, sizeRatioDB, meanSizeRatioDB) 44 | }).Methods("GET", "POST", "PATCH", "HEAD", "OPTIONS", "PUT") 45 | router.HandleFunc("/upload/{asset_id}", func(w http.ResponseWriter, r *http.Request) { 46 | routes.UploadStatusHandler(w, r, uploadDB) 47 | }).Methods("GET", http.MethodOptions) 48 | 49 | log.Info("Starting server at PORT", serverPort) 50 | log.Fatal("Error in starting server", http.ListenAndServe(serverPort, router)) 51 | } 52 | -------------------------------------------------------------------------------- /util/files.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "os" 7 | ) 8 | 9 | // ReadLines reads a whole file into memory and returns a slice of its lines. 10 | func ReadLines(path string) ([]string, error) { 11 | file, err := os.Open(path) 12 | if err != nil { 13 | return nil, err 14 | } 15 | defer file.Close() 16 | 17 | var lines []string 18 | scanner := bufio.NewScanner(file) 19 | for scanner.Scan() { 20 | lines = append(lines, scanner.Text()) 21 | } 22 | return lines, scanner.Err() 23 | } 24 | 25 | // WriteLines writes the lines to the given file. 26 | func WriteLines(lines []string, path string) error { 27 | file, err := os.Create(path) 28 | if err != nil { 29 | return err 30 | } 31 | defer file.Close() 32 | 33 | w := bufio.NewWriter(file) 34 | for _, line := range lines { 35 | fmt.Fprintln(w, line) 36 | } 37 | return w.Flush() 38 | } 39 | -------------------------------------------------------------------------------- /util/livepeer.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "io/ioutil" 7 | "math/big" 8 | "net/http" 9 | "os" 10 | "os/exec" 11 | "strconv" 12 | 13 | log "github.com/sirupsen/logrus" 14 | ) 15 | 16 | // OrchestratorStat is an object that is received from the livepeer pricing tool. 17 | type OrchestratorStat struct { 18 | Address string `json:"Address"` 19 | ServiceURI string `json:"ServiceURI"` 20 | LastRewardRound int `json:"LastRewardRound"` 21 | RewardCut int `json:"RewardCut"` 22 | FeeShare int `json:"FeeShare"` 23 | DelegatedStake *big.Int `json:"DelegatedStake"` 24 | ActivationRound int `json:"ActivationRound"` 25 | DeactivationRound *big.Int `json:"DeactivationRound"` 26 | Active bool `json:"Active"` 27 | Status string `json:"Status"` 28 | PricePerPixel float64 `json:"PricePerPixel"` 29 | UpdatedAt int `json:"UpdatedAt"` 30 | } 31 | 32 | // GetOrchestratorStats returns an array of OrchestratorStats 33 | func GetOrchestratorStats(body []byte) ([]OrchestratorStat, error) { 34 | var s = new([]OrchestratorStat) 35 | err := json.Unmarshal(body, &s) 36 | if err != nil { 37 | return nil, err 38 | } 39 | return *s, nil 40 | } 41 | 42 | // GetPixelsInRendition returns the number of pixels in a particular rendition of a video. 43 | func GetPixelsInRendition(width int, height int, fps int, numStreams int, duration int) int { 44 | return width * height * fps * numStreams * duration 45 | } 46 | 47 | // GetTotalPixels returns the total pixels for the 3 renditions combined. 48 | // :param duration: duration of video in seconds 49 | func GetTotalPixels(duration int) int { 50 | pixels1080p := GetPixelsInRendition(1920, 1080, 30, 1, duration) 51 | pixels720p := GetPixelsInRendition(1280, 720, 30, 1, duration) 52 | pixels360p := GetPixelsInRendition(640, 360, 30, 1, duration) 53 | 54 | return pixels1080p + pixels720p + pixels360p 55 | } 56 | 57 | // CalculateTranscodingCost computes the transcoding cost 58 | // of a video in wei and returns it. 59 | func CalculateTranscodingCost(fileName string, duration float64) (*big.Int, error) { 60 | // var transcodingCostEstimated uint64 61 | transcodingCostEstimated := new(big.Int) 62 | 63 | if duration == 0 && fileName != "" { 64 | stdout, err := exec.Command("ffprobe", "-i", fileName, "-show_entries", "format=duration", "-v", "quiet", "-of", "csv=p=0").Output() 65 | if err != nil { 66 | return transcodingCostEstimated, fmt.Errorf("finding video duration: %s", err) 67 | } 68 | duration, err = strconv.ParseFloat(string(stdout)[:len(string(stdout))-2], 64) 69 | if err != nil { 70 | return transcodingCostEstimated, fmt.Errorf("finding video duration: %s", err) 71 | } 72 | } 73 | log.Info("fileName", fileName, "duration", duration) 74 | 75 | // Fetch orchestrator stats from livepeer pricing tool: 76 | // GET https://livepeer-pricing-tool.com/orchestratorStats 77 | 78 | livepeerPricingToolURL, livepeerPricingToolURLExists := os.LookupEnv("LIVEPEER_PRICING_TOOL") 79 | if !livepeerPricingToolURLExists { 80 | return transcodingCostEstimated, fmt.Errorf("`LIVEPEER_PRICING_TOOL` env variable not provided") 81 | } 82 | 83 | var orchestratorStats string 84 | if livepeerPricingToolURL[len(livepeerPricingToolURL)-1:] == "/" { 85 | orchestratorStats = livepeerPricingToolURL + "orchestratorStats" 86 | } else { 87 | orchestratorStats = livepeerPricingToolURL + "/orchestratorStats" 88 | } 89 | 90 | resp, err := http.Get(orchestratorStats) 91 | if err != nil { 92 | return transcodingCostEstimated, fmt.Errorf("couldn't fetch orchestrator stats: %s", err) 93 | } 94 | 95 | defer resp.Body.Close() 96 | 97 | body, err := ioutil.ReadAll(resp.Body) 98 | if err != nil { 99 | return transcodingCostEstimated, fmt.Errorf("reading the orchestrator stats: %s", err) 100 | } 101 | 102 | orchStats, err := GetOrchestratorStats([]byte(body)) 103 | if err != nil { 104 | return transcodingCostEstimated, fmt.Errorf("getting the orchestrator stats: %s", err) 105 | } 106 | 107 | weightSum := big.NewInt(0) 108 | productSum := big.NewFloat(0) 109 | 110 | for _, i := range orchStats { 111 | stake := new(big.Float).SetInt(i.DelegatedStake) 112 | ppp := new(big.Float).SetFloat64(i.PricePerPixel) 113 | product := stake.Mul(stake, ppp) 114 | 115 | weightSum.Add(weightSum, i.DelegatedStake) 116 | productSum.Add(productSum, product) 117 | } 118 | 119 | // Calculate weighted average price per pixel (weighted by Delegated Stake) 120 | 121 | // Weighted pricePerPixel 122 | pricePerPixel := new(big.Float).Quo(productSum, new(big.Float).SetInt(weightSum)) 123 | 124 | pixels := GetTotalPixels(int(duration)) 125 | 126 | // Calculate livepeer price for uploaded video 127 | 128 | livepeerPrice := new(big.Float).SetInt(big.NewInt(int64(1))) 129 | livepeerPrice = livepeerPrice.Mul(new(big.Float).SetInt(big.NewInt(int64(pixels))), pricePerPixel) 130 | 131 | // Transcoding cost of the video in wei 132 | livepeerPrice.Int(transcodingCostEstimated) // store converted number in result 133 | 134 | log.Info("livepeer transcodingCostEstimated", transcodingCostEstimated) 135 | 136 | return transcodingCostEstimated, nil 137 | } 138 | -------------------------------------------------------------------------------- /util/multipart_uploader.go: -------------------------------------------------------------------------------- 1 | /* 2 | This file has been taken from https://github.com/ItalyPaleAle/pinatapinner/blob/master/multipart-uploader.go 3 | */ 4 | 5 | /* Adapted from https://github.com/ipsusila/gogo/blob/master/http/formuploader.go */ 6 | 7 | /* 8 | MIT License 9 | Copyright (c) 2017 I Putu Susila 10 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 11 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 12 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 13 | */ 14 | 15 | package util 16 | 17 | import ( 18 | "bytes" 19 | "fmt" 20 | "io" 21 | "mime/multipart" 22 | "net/http" 23 | "os" 24 | "path/filepath" 25 | ) 26 | 27 | //FormUploader represents HTTP multipart form submission. 28 | type FormUploader interface { 29 | AddField(name, value string) FormUploader 30 | AddFields(fields map[string]string) FormUploader 31 | Fields(name string) []string 32 | AddFiles(fieldName string, basePath string, files ...string) error 33 | Files() []string 34 | SetChunkSize(size int64) FormUploader 35 | ChunkSize() int64 36 | Post(client *http.Client, targetURL string, headers map[string]string) (*http.Response, error) 37 | Put(client *http.Client, targetURL string, headers map[string]string) (*http.Response, error) 38 | } 39 | 40 | type formPart interface { 41 | newPart(buf *bytes.Buffer, mpw *multipart.Writer) (int64, error) 42 | writeTo(chunk []byte, w io.Writer) error 43 | close() error 44 | } 45 | 46 | type fieldPart struct { 47 | name string //field name 48 | value string //field value 49 | mpData []byte //multipart data 50 | } 51 | 52 | type filePart struct { 53 | file *os.File //File handler 54 | fileSize int64 //File size 55 | baseName string //Base name (may differs from orignal base-name) 56 | filePath string //Original filename 57 | fieldName string //Name of field in multipart content 58 | mpBegin []byte //Beginning of the multipart 59 | } 60 | 61 | type endPart struct { 62 | mpData []byte //multipart data 63 | } 64 | 65 | type formUploader struct { 66 | chunkSize int64 67 | fields []*fieldPart 68 | files []*filePart 69 | } 70 | 71 | //NewFormUploader creates form uploder instance. 72 | func NewFormUploader() FormUploader { 73 | return &formUploader{chunkSize: 1024 * 10} 74 | } 75 | 76 | //Write all the data to writer. 77 | func writeExactly(w io.Writer, data []byte) error { 78 | if ndata := len(data); ndata > 0 { 79 | nw := 0 80 | for nw < ndata { 81 | n, err := w.Write(data[nw:]) 82 | if err != nil { 83 | return err 84 | } 85 | nw += n 86 | } 87 | } 88 | return nil 89 | } 90 | 91 | func (p *fieldPart) newPart(buf *bytes.Buffer, mpw *multipart.Writer) (int64, error) { 92 | //Create multipart data 93 | if err := mpw.WriteField(p.name, p.value); err != nil { 94 | return 0, err 95 | } 96 | 97 | //Read writen data from buffer 98 | n := buf.Len() 99 | if cap(p.mpData) < n { 100 | p.mpData = make([]byte, n) 101 | } 102 | nr, err := buf.Read(p.mpData) 103 | if err != nil { 104 | return 0, err 105 | } 106 | //correctly assign data len 107 | p.mpData = p.mpData[:nr] 108 | 109 | return int64(nr), nil 110 | } 111 | func (p *fieldPart) writeTo(chunk []byte, w io.Writer) error { 112 | //chunk is not used. 113 | return writeExactly(w, p.mpData) 114 | } 115 | func (p *fieldPart) close() error { 116 | //do nothing 117 | return nil 118 | } 119 | 120 | func (p *filePart) newPart(buf *bytes.Buffer, mpw *multipart.Writer) (int64, error) { 121 | //make sure file is closed 122 | if err := p.close(); err != nil { 123 | return 0, err 124 | } 125 | 126 | //open file and get information 127 | file, err := os.Open(p.filePath) 128 | if err != nil { 129 | return 0, err 130 | } 131 | fi, err := file.Stat() 132 | if err != nil { 133 | return 0, err 134 | } 135 | p.file = file 136 | p.fileSize = fi.Size() 137 | 138 | //Create file part (the content is not writen) 139 | if _, err := mpw.CreateFormFile(p.fieldName, p.baseName); err != nil { 140 | return 0, err 141 | } 142 | 143 | n := buf.Len() 144 | if cap(p.mpBegin) < n { 145 | p.mpBegin = make([]byte, n) 146 | } 147 | nr, err := buf.Read(p.mpBegin) 148 | if err != nil { 149 | return int64(nr), err 150 | } 151 | //correctly assign data len 152 | p.mpBegin = p.mpBegin[:nr] 153 | 154 | return int64(n) + p.fileSize, nil 155 | } 156 | func (p *filePart) writeTo(chunk []byte, w io.Writer) error { 157 | //write multipart begin 158 | if err := writeExactly(w, p.mpBegin); err != nil { 159 | return err 160 | } 161 | 162 | if nw, err := io.CopyBuffer(w, p.file, chunk); err != nil { 163 | return err 164 | } else if nw != p.fileSize { 165 | //size doesn't match 166 | return fmt.Errorf("file size (%v) != copy size (%v)", p.fileSize, nw) 167 | } 168 | 169 | return nil 170 | } 171 | func (p *filePart) close() error { 172 | if f := p.file; f != nil { 173 | p.file = nil 174 | if err := f.Close(); err != nil { 175 | return err 176 | } 177 | } 178 | return nil 179 | } 180 | 181 | func (p *endPart) newPart(buf *bytes.Buffer, mpw *multipart.Writer) (int64, error) { 182 | //end boundary 183 | if err := mpw.Close(); err != nil { 184 | return 0, err 185 | } 186 | 187 | //Read writen data from buffer 188 | n := buf.Len() 189 | if cap(p.mpData) < n { 190 | p.mpData = make([]byte, n) 191 | } 192 | nr, err := buf.Read(p.mpData) 193 | if err != nil { 194 | return 0, err 195 | } 196 | //correctly assign data len 197 | p.mpData = p.mpData[:nr] 198 | 199 | return int64(nr), nil 200 | 201 | } 202 | func (p *endPart) writeTo(chunk []byte, w io.Writer) error { 203 | //chunk is not used. 204 | return writeExactly(w, p.mpData) 205 | } 206 | func (p *endPart) close() error { 207 | return nil 208 | } 209 | 210 | func (fu *formUploader) AddField(name, value string) FormUploader { 211 | fp := &fieldPart{name: name, value: value} 212 | fu.fields = append(fu.fields, fp) 213 | 214 | return fu 215 | } 216 | func (fu *formUploader) AddFields(fields map[string]string) FormUploader { 217 | for key, val := range fields { 218 | fp := &fieldPart{name: key, value: val} 219 | fu.fields = append(fu.fields, fp) 220 | } 221 | return fu 222 | } 223 | func (fu *formUploader) Fields(name string) []string { 224 | fields := []string{} 225 | for _, field := range fu.fields { 226 | if field.name == name { 227 | fields = append(fields, field.value) 228 | } 229 | } 230 | return fields 231 | } 232 | func (fu *formUploader) AddFiles(fieldName string, basePath string, files ...string) (err error) { 233 | basePath, err = filepath.Abs(basePath) 234 | if err != nil { 235 | return 236 | } 237 | for _, file := range files { 238 | fp := &filePart{ 239 | fieldName: fieldName, 240 | filePath: filepath.Join(basePath, file), 241 | baseName: "drop/" + file, 242 | } 243 | fu.files = append(fu.files, fp) 244 | } 245 | return 246 | } 247 | func (fu *formUploader) Files() []string { 248 | filePaths := []string{} 249 | for _, fp := range fu.files { 250 | filePaths = append(filePaths, fp.filePath) 251 | } 252 | return filePaths 253 | } 254 | func (fu *formUploader) SetChunkSize(size int64) FormUploader { 255 | fu.chunkSize = size 256 | return fu 257 | } 258 | func (fu *formUploader) ChunkSize() int64 { 259 | return fu.chunkSize 260 | } 261 | func (fu *formUploader) Post(client *http.Client, targetURL string, headers map[string]string) (*http.Response, error) { 262 | return fu.submit(client, targetURL, "POST", headers) 263 | } 264 | func (fu *formUploader) Put(client *http.Client, targetURL string, headers map[string]string) (*http.Response, error) { 265 | return fu.submit(client, targetURL, "PUT", headers) 266 | } 267 | func (fu *formUploader) submit(client *http.Client, targetURL, method string, headers map[string]string) (*http.Response, error) { 268 | buf := &bytes.Buffer{} 269 | mpw := multipart.NewWriter(buf) 270 | 271 | //List of form parts: fields, files, end 272 | parts := []formPart{} 273 | for _, p := range fu.fields { 274 | parts = append(parts, p) 275 | } 276 | for _, p := range fu.files { 277 | parts = append(parts, p) 278 | } 279 | parts = append(parts, &endPart{}) 280 | 281 | //create parts and calculate size. 282 | totalContentLen := int64(0) 283 | for _, p := range parts { 284 | n, err := p.newPart(buf, mpw) 285 | if err != nil { 286 | return nil, err 287 | } 288 | totalContentLen += n 289 | } 290 | 291 | //close form parts when done. 292 | defer func() { 293 | for _, p := range parts { 294 | p.close() 295 | } 296 | }() 297 | 298 | //Pipe for connecting reader and writer. 299 | //Reader side will be connected to request, 300 | //while writer side will be used for writing 301 | //multipart form content. 302 | reader, writer := io.Pipe() 303 | defer reader.Close() 304 | 305 | //Write parts content 306 | var routineErr error 307 | go func() { 308 | defer writer.Close() 309 | 310 | //allocate buffer for reading file. 311 | chunk := make([]byte, fu.chunkSize) 312 | for _, p := range parts { 313 | if err := p.writeTo(chunk, writer); err != nil { 314 | routineErr = err 315 | break 316 | } 317 | } 318 | }() 319 | 320 | //construct HTTP client Request with rd 321 | req, err := http.NewRequest(method, targetURL, reader) 322 | if err != nil { 323 | return nil, err 324 | } 325 | 326 | //user headers 327 | if len(headers) > 0 { 328 | for k, v := range headers { 329 | req.Header.Set(k, v) 330 | } 331 | } 332 | 333 | //required headers 334 | req.Header.Set("Content-Type", mpw.FormDataContentType()) 335 | req.ContentLength = totalContentLen 336 | 337 | //process request 338 | resp, err := client.Do(req) 339 | if err != nil { 340 | return nil, err 341 | } else if routineErr != nil { 342 | return nil, routineErr 343 | } 344 | 345 | return resp, nil 346 | } 347 | -------------------------------------------------------------------------------- /util/pinata.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "io/ioutil" 7 | "net/http" 8 | "os" 9 | "path/filepath" 10 | "strings" 11 | ) 12 | 13 | const endpoint = "https://api.pinata.cloud/pinning/pinFileToIPFS" 14 | 15 | // PinFolder pins a folder 16 | func PinFolder(folder string, name string) (string, error) { 17 | var pinataCID string 18 | 19 | // Build the request 20 | fu := NewFormUploader() 21 | 22 | // Scan for files and add them 23 | files := make([]string, 0) 24 | err := filepath.Walk(folder, 25 | func(path string, info os.FileInfo, err error) error { 26 | if err != nil { 27 | return err 28 | } 29 | // Add files only 30 | if info.Mode().IsRegular() { 31 | // Remove the folder from the beginning of the file's name 32 | path = strings.TrimPrefix(path, folder+"/") 33 | // Trim again an optional path separator 34 | path = strings.TrimPrefix(path, string(os.PathSeparator)) 35 | files = append(files, path) 36 | } 37 | return nil 38 | }) 39 | if err != nil { 40 | return pinataCID, err 41 | } 42 | fu.AddFiles("file", folder, files...) 43 | 44 | // Add the name 45 | keyValues := make(map[string]string) 46 | keyValues["PinnedBy"] = "Demux" 47 | pinataMetadata := struct { 48 | Name string `json:"name"` 49 | KeyValues map[string]string `json:"keyvalues"` 50 | }{ 51 | Name: name, 52 | KeyValues: keyValues, 53 | } 54 | pinataMetadataJSON, err := json.Marshal(pinataMetadata) 55 | if err != nil { 56 | return pinataCID, err 57 | } 58 | fu.AddField("pinataMetadata", string(pinataMetadataJSON)) 59 | 60 | pinataOptions := struct { 61 | CidVersion int `json:"cidVersion"` 62 | }{ 63 | CidVersion: 1, 64 | } 65 | pinataOptionsJSON, err := json.Marshal(pinataOptions) 66 | if err != nil { 67 | return pinataCID, err 68 | } 69 | fu.AddField("pinataOptions", string(pinataOptionsJSON)) 70 | 71 | // Send the request 72 | client := &http.Client{ 73 | // Do not set a timeout, as the files might be large 74 | Timeout: 0, 75 | } 76 | headers := make(map[string]string, 2) 77 | headers["pinata_api_key"] = os.Getenv("PINATA_API_KEY") 78 | headers["pinata_secret_api_key"] = os.Getenv("PINATA_SECRET_KEY") 79 | resp, err := fu.Post(client, endpoint, headers) 80 | if err != nil { 81 | return pinataCID, err 82 | } 83 | 84 | // Get the response 85 | res, err := ioutil.ReadAll(resp.Body) 86 | if err != nil { 87 | return pinataCID, err 88 | } 89 | 90 | // If status code isn't 2xx, we have an error 91 | if resp.StatusCode < 200 || resp.StatusCode > 299 { 92 | return pinataCID, fmt.Errorf("Invalid response status code: %d", resp.StatusCode) 93 | } 94 | 95 | // Output the response (should be JSON) 96 | var j = []byte(string(res)) 97 | 98 | // a map container to decode the JSON structure into 99 | c := make(map[string]json.RawMessage) 100 | // unmarschal JSON 101 | e := json.Unmarshal(j, &c) 102 | // panic on error 103 | if e != nil { 104 | return pinataCID, e 105 | } 106 | // a string slice to hold the keys 107 | k := make([]string, len(c)) 108 | // iteration counter 109 | i := 0 110 | // copy c's keys into k 111 | for s, v := range c { 112 | k[i] = s 113 | if s == "IpfsHash" { 114 | pinataCID = strings.TrimPrefix(strings.TrimSuffix(string(v), "\""), "\"") 115 | } 116 | i++ 117 | } 118 | 119 | return pinataCID, nil 120 | } 121 | -------------------------------------------------------------------------------- /util/poller.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "os" 7 | "strconv" 8 | "strings" 9 | "time" 10 | 11 | "github.com/buidl-labs/Demux/dataservice" 12 | // "github.com/buidl-labs/Demux/internal" 13 | "github.com/buidl-labs/Demux/model" 14 | 15 | "github.com/ipfs/go-cid" 16 | log "github.com/sirupsen/logrus" 17 | "github.com/textileio/powergate/v2/api/client" 18 | powc "github.com/textileio/powergate/v2/api/client" 19 | userPb "github.com/textileio/powergate/v2/api/gen/powergate/user/v1" 20 | "github.com/textileio/powergate/v2/ffs" 21 | // "github.com/textileio/powergate/v2/api/client/admin" 22 | // "google.golang.org/protobuf/encoding/protojson" 23 | ) 24 | 25 | // RunPoller runs a poller in the background which 26 | // updates the state of storage deal jobs. 27 | func RunPoller(db dataservice.DatabaseHelper) { 28 | assetDB := dataservice.NewAssetDatabase(db) 29 | storageDealDB := dataservice.NewStorageDealDatabase(db) 30 | 31 | i, err := strconv.Atoi(os.Getenv("POLL_INTERVAL")) 32 | if err != nil { 33 | log.Error("Please set env variable `POLL_INTERVAL`") 34 | return 35 | } 36 | var pollInterval = time.Minute * time.Duration(i) 37 | 38 | ctx, cancel := context.WithCancel(context.Background()) 39 | defer cancel() 40 | pgClient, _ := powc.NewClient(InitialPowergateSetup.PowergateAddr) 41 | defer func() { 42 | if err := pgClient.Close(); err != nil { 43 | log.Errorf("closing powergate client: %s", err) 44 | } 45 | }() 46 | for { 47 | select { 48 | case <-ctx.Done(): 49 | log.Info("shutting down archive tracker daemon") 50 | return 51 | case <-time.After(pollInterval): 52 | deals, err := storageDealDB.GetPendingDeals() 53 | if err != nil { 54 | return 55 | } 56 | log.Infof("Number of pending storage deals: %d\n", len(deals)) 57 | for _, deal := range deals { 58 | cidcorrtype, _ := cid.Decode(deal.CID) 59 | b, s, err := pollStorageDealProgress(ctx, pgClient, ffs.JobID(deal.JobID), cidcorrtype, deal, storageDealDB, assetDB) 60 | log.Info("dealJobID", deal.JobID, "pollprog", b, s, err) 61 | } 62 | } 63 | } 64 | } 65 | 66 | func pollStorageDealProgress(ctx context.Context, pgClient *powc.Client, jid ffs.JobID, mycid cid.Cid, storageDeal model.StorageDeal, storageDealDB dataservice.StorageDealDatabase, assetDB dataservice.AssetDatabase) (bool, string, error) { 67 | ctx = context.WithValue(ctx, powc.AuthKey, storageDeal.FFSToken) 68 | 69 | chJob := make(chan powc.WatchStorageJobsEvent, 1) 70 | ctxWatch, cancel := context.WithCancel(ctx) 71 | defer cancel() 72 | if err := pgClient.StorageJobs.Watch(ctxWatch, chJob, jid.String()); err != nil { 73 | // return fmt.Errorf("opening listening job status: %s", err) 74 | 75 | // if error specifies that the auth token isn't found, powergate must have been reset. 76 | // return the error as fatal so the archive will be untracked 77 | if strings.Contains(err.Error(), "auth token not found") { 78 | return false, "", err 79 | } 80 | return true, fmt.Sprintf("watching current job %s for cid %s: %s", jid, mycid, err), nil 81 | } 82 | 83 | // var s powc.WatchStorageJobsEvent 84 | 85 | var aborted bool 86 | var abortMsg string 87 | var storageJob *userPb.StorageJob 88 | select { 89 | case <-ctx.Done(): 90 | log.Infof("job %s status watching canceled\n", jid) 91 | return true, "watching cancelled", nil 92 | case s, ok := <-chJob: 93 | if !ok { 94 | return true, "powergate closed communication chan", nil 95 | } 96 | if s.Err != nil { 97 | log.Errorf("job %s update: %s", jid, s.Err) 98 | aborted = true 99 | abortMsg = s.Err.Error() 100 | } 101 | storageJob = s.Res.StorageJob 102 | } 103 | 104 | if !aborted && !isJobStatusFinal(storageJob) { 105 | return true, "no final status yet", nil 106 | } 107 | 108 | // On success, save Deal data in the underlying Bucket thread. On failure, 109 | // save the error message. Also update status on Mongo for the archive. 110 | if storageJob.Status == userPb.JobStatus_JOB_STATUS_SUCCESS { 111 | err := saveDealsInDB(ctx, pgClient, storageDeal.FFSToken, mycid, storageDealDB, assetDB) 112 | if err != nil { 113 | return true, fmt.Sprintf("saving deal data in archive: %s", err), nil 114 | } 115 | } else { 116 | log.Info("job.Status", storageJob.Status, storageJob.Status.String()) 117 | storageDealDB.UpdateStorageDeal(mycid.String(), 2, "failed to create filecoin storage deal", "", "", 0) 118 | } 119 | 120 | msg := "reached final status" 121 | if aborted { 122 | msg = "aborted with reason " + abortMsg 123 | } 124 | 125 | return false, msg, nil 126 | } 127 | 128 | func saveDealsInDB(ctx context.Context, pgClient *powc.Client, ffsToken string, c cid.Cid, storageDealDB dataservice.StorageDealDatabase, assetDB dataservice.AssetDatabase) error { 129 | ctx = context.WithValue(ctx, powc.AuthKey, ffsToken) 130 | conf := powc.ListConfig{ 131 | Select: client.Executing, 132 | } 133 | res, err := pgClient.StorageJobs.List(ctx, conf) 134 | if err != nil { 135 | return fmt.Errorf("getting executing storage jobs: %s", err) 136 | } 137 | // sh, err := pgClient.FFS.Show(ctxFFS, c) 138 | // if err != nil { 139 | // return fmt.Errorf("getting cid info: %s", err) 140 | // } 141 | 142 | log.Info("sdidb res:", res) 143 | 144 | // proposals := sh.GetCidInfo().GetCold().GetFilecoin().GetProposals() 145 | 146 | // log.Info("proposals", proposals) 147 | 148 | // if len(proposals) > 0 { 149 | // for _, prop := range proposals { 150 | // priceAttoFIL := prop.EpochPrice * uint64(prop.Duration) 151 | // priceAttoFILBigInt := new(big.Int).SetUint64(priceAttoFIL) 152 | // priceFIL := float64(priceAttoFIL) * math.Pow(10, -18) 153 | // log.Info("priceAttoFIL", priceAttoFIL, "priceAttoFILBigInt", priceAttoFILBigInt, "priceFIL", priceFIL) 154 | 155 | // log.Info("ProposalCid", prop.ProposalCid) 156 | // log.Info("Renewed", prop.Renewed) 157 | // log.Info("Miner", prop.Miner) 158 | // log.Info("StartEpoch", prop.StartEpoch) 159 | // log.Info("ActivationEpoch", prop.ActivationEpoch) 160 | // log.Info("Duration", prop.Duration) 161 | // log.Info("EpochPrice", prop.EpochPrice) 162 | 163 | // storageDealDB.UpdateStorageDeal(c.String(), 1, internal.AssetStatusMap[4], prop.Miner, priceAttoFILBigInt.String(), 0) 164 | // sDeal, err := storageDealDB.GetStorageDealByCID(c.String()) 165 | // if err == nil { 166 | // assetID := sDeal.AssetID 167 | // assetDB.UpdateAssetStatus(assetID, 4, internal.AssetStatusMap[4], false) 168 | // } 169 | // } 170 | // } 171 | 172 | return nil 173 | } 174 | 175 | func isJobStatusFinal(sJ *userPb.StorageJob) bool { 176 | return sJ.Status == userPb.JobStatus_JOB_STATUS_SUCCESS || 177 | sJ.Status == userPb.JobStatus_JOB_STATUS_CANCELED || 178 | sJ.Status == userPb.JobStatus_JOB_STATUS_FAILED 179 | } 180 | -------------------------------------------------------------------------------- /util/pow.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "math/big" 7 | "os" 8 | "strings" 9 | "time" 10 | 11 | // "github.com/ipfs/go-cid" 12 | 13 | log "github.com/sirupsen/logrus" 14 | "github.com/textileio/powergate/v2/api/client" 15 | 16 | // "github.com/textileio/powergate/ffs" 17 | // "github.com/textileio/powergate/health" 18 | // "google.golang.org/protobuf/encoding/protojson" 19 | userPb "github.com/textileio/powergate/v2/api/gen/powergate/user/v1" 20 | ) 21 | 22 | // PowergateSetup initializes stuff 23 | type PowergateSetup struct { 24 | PowergateAddr string 25 | SampleSize int64 26 | MaxParallel int 27 | TotalSamples int 28 | } 29 | 30 | var ( 31 | powergateAddr = os.Getenv("POWERGATE_ADDR") 32 | ipfsRevProxyAddr = os.Getenv("IPFS_REV_PROXY_ADDR") 33 | trustedMinersStr = os.Getenv("TRUSTED_MINERS") 34 | trustedMiners = strings.Fields(trustedMinersStr) 35 | epochDurationSeconds = 30 36 | minDealDuration = 180 * (24 * 60 * 60 / epochDurationSeconds) 37 | ) 38 | 39 | // InitialPowergateSetup creates an instance of PowergateSetup 40 | var InitialPowergateSetup = PowergateSetup{ 41 | PowergateAddr: powergateAddr, 42 | SampleSize: 700, 43 | MaxParallel: 1, 44 | TotalSamples: 1, 45 | } 46 | 47 | // CalculateStorageCost computes the storage cost 48 | // of a folder in attoFIL and returns it. 49 | func CalculateStorageCost(folderSize uint64, storageDuration int64) (*big.Int, error) { 50 | estimatedPrice := big.NewInt(0) 51 | // duration := float64(storageDuration) // duration of deal in seconds (provided by user) 52 | // epochs := float64(duration / float64(30)) 53 | // log.Info("folderSize", folderSize) 54 | // log.Info("duration", duration, "epochs", epochs) 55 | 56 | // ctx, cancel := context.WithCancel(context.Background()) 57 | // defer cancel() 58 | // pgClient, _ := client.NewClient(InitialPowergateSetup.PowergateAddr) 59 | // defer func() { 60 | // if err := pgClient.Close(); err != nil { 61 | // log.Warn("closing powergate client:", err) 62 | // } 63 | // }() 64 | 65 | // index, err := pgClient.Asks.Get(ctx) 66 | // if err != nil { 67 | // log.Warn("getting asks:", err) 68 | // return estimatedPrice, err 69 | // } 70 | // if len(index.Storage) > 0 { 71 | // i := 0 72 | // pricesSum := big.NewInt(0) 73 | // for _, ask := range index.Storage { 74 | // currPrice := big.NewInt(int64(ask.Price)) 75 | // pricesSum.Add(pricesSum, currPrice) 76 | // i++ 77 | // } 78 | // lenIdx := big.NewInt(int64(len(index.Storage))) 79 | // meanEpochPrice := new(big.Int).Div(pricesSum, lenIdx) 80 | // epochsBigInt := big.NewInt(int64(epochs)) 81 | // folderSizeBigInt := big.NewInt(int64(folderSize)) 82 | // bigInt1024 := big.NewInt(1024) 83 | // estimatedPrice.Mul(meanEpochPrice, epochsBigInt) 84 | // estimatedPrice.Mul(estimatedPrice, folderSizeBigInt) 85 | // estimatedPrice = new(big.Int).Div(estimatedPrice, bigInt1024) 86 | // log.Info("estimatedPrice", estimatedPrice, ", meanEpochPrice", meanEpochPrice, ", pricesSum", pricesSum) 87 | // return estimatedPrice, nil 88 | // } 89 | // return estimatedPrice, fmt.Errorf("no miners in asks index") 90 | 91 | return estimatedPrice, nil // powergate v1 doesn't let us get Asks index, so return price=0 92 | } 93 | 94 | // RunPow runs the powergate client 95 | func RunPow(ctx context.Context, setup PowergateSetup, fName string) (string, string, string, string, string, int, int, bool, error) { 96 | var currCid string 97 | var minerName string 98 | var tok string 99 | var jid string 100 | var storagePrice int 101 | var expiry int 102 | var staged bool = false 103 | var powCloseError error 104 | 105 | // Create a new powergate client 106 | c, err := client.NewClient(setup.PowergateAddr) 107 | defer func() { 108 | if err := c.Close(); err != nil { 109 | log.Errorf("closing powergate client: %s", err) 110 | powCloseError = err 111 | } 112 | }() 113 | if err != nil { 114 | return currCid, fName, minerName, tok, jid, storagePrice, expiry, staged, fmt.Errorf("creating client: %s", err) 115 | } 116 | 117 | // if err := sanityCheck(ctx, c); err != nil { 118 | // log.Error(err) 119 | // return currCid, fName, minerName, tok, jid, storagePrice, expiry, staged, fmt.Errorf("sanity check with client: %s", err) 120 | // } 121 | 122 | if currCid, fName, minerName, tok, jid, storagePrice, expiry, staged, err = runSetup(ctx, c, setup, fName); err != nil { 123 | return currCid, fName, minerName, tok, jid, storagePrice, expiry, staged, fmt.Errorf("running test setup: %s", err) 124 | } 125 | 126 | if powCloseError != nil { 127 | return currCid, fName, minerName, tok, jid, storagePrice, expiry, staged, powCloseError 128 | } 129 | return currCid, fName, minerName, tok, jid, storagePrice, expiry, staged, nil 130 | } 131 | 132 | // func sanityCheck(ctx context.Context, c *client.Client) error { 133 | // s, _, err := c.Health.Check(ctx) 134 | // if err != nil { 135 | // return fmt.Errorf("health check call: %s", err) 136 | // } 137 | // if s != health.Ok { 138 | // return fmt.Errorf("reported health check not Ok: %s", s) 139 | // } 140 | // return nil 141 | // } 142 | 143 | func runSetup(ctx context.Context, c *client.Client, setup PowergateSetup, fName string) (string, string, string, string, string, int, int, bool, error) { 144 | 145 | var currCid string 146 | var jid string 147 | var minerName string 148 | var storagePrice int 149 | var expiry int 150 | var staged bool = false 151 | 152 | tok := os.Getenv("POW_TOKEN") 153 | 154 | log.Infof("ffs tok: [%s]\n", tok) 155 | 156 | ctx = context.WithValue(ctx, client.AuthKey, tok) 157 | 158 | // info, err := c.FFS.Info(ctx) 159 | // if err != nil { 160 | // return currCid, fName, minerName, tok, jid, storagePrice, expiry, staged, fmt.Errorf("getting instance info: %s", err) 161 | // } 162 | 163 | // // Asks index 164 | // index, err := c.Asks.Get(ctx) 165 | // if err != nil { 166 | // return currCid, fName, minerName, tok, jid, storagePrice, expiry, staged, fmt.Errorf("getting asks index: %s", err) 167 | // } 168 | 169 | // if len(index.Storage) > 0 { 170 | // log.Printf("Storage median price: %v\n", index.StorageMedianPrice) 171 | // log.Printf("Last updated: %v\n", index.LastUpdated.Format("01/02/06 15:04 MST")) 172 | // } 173 | minerName = "nil" 174 | storagePrice = 0 175 | expiry = 0 176 | 177 | // wallet address 178 | res, err := c.Wallet.Addresses(ctx) 179 | if err != nil { 180 | return currCid, fName, minerName, tok, jid, storagePrice, expiry, staged, fmt.Errorf("getting instance info: %s", err) 181 | } 182 | addr := res.Addresses[0].Address 183 | time.Sleep(time.Second * 5) 184 | 185 | chLimit := make(chan struct{}, setup.MaxParallel) 186 | chErr := make(chan error, setup.TotalSamples) 187 | for i := 0; i < setup.TotalSamples; i++ { 188 | chLimit <- struct{}{} 189 | go func(i int) { 190 | defer func() { <-chLimit }() 191 | if currCid, fName, minerName, tok, jid, storagePrice, expiry, staged, err = run(ctx, c, i, setup.SampleSize, addr, fName, minerName, tok, storagePrice, expiry); err != nil { 192 | chErr <- fmt.Errorf("failed run %d: %s", i, err) 193 | } else { 194 | // no errors 195 | log.Infof("cid: [%s] fName: [%s]\n", currCid, fName) 196 | } 197 | }(i) 198 | } 199 | for i := 0; i < setup.MaxParallel; i++ { 200 | chLimit <- struct{}{} 201 | } 202 | close(chErr) 203 | for err := range chErr { 204 | return currCid, fName, minerName, tok, jid, storagePrice, expiry, staged, fmt.Errorf("sample run errored: %s", err) 205 | } 206 | 207 | return currCid, fName, minerName, tok, jid, storagePrice, expiry, staged, nil 208 | } 209 | 210 | func run(ctx context.Context, c *client.Client, id int, size int64, addr string, fName string, minerName string, tok string, storagePrice int, expiry int) (string, string, string, string, string, int, int, bool, error) { 211 | log.Infof("[%d] Executing run...\n", id) 212 | defer log.Infof("[%d] Done\n", id) 213 | 214 | var ci string 215 | var jid string 216 | var staged bool = false 217 | 218 | fi, err := os.Stat(fName) 219 | if os.IsNotExist(err) { 220 | return ci, fName, minerName, tok, jid, storagePrice, expiry, staged, fmt.Errorf("file/folder doesn't exist: %s", err) 221 | } 222 | if err != nil { 223 | return ci, fName, minerName, tok, jid, storagePrice, expiry, staged, fmt.Errorf("getting file/folder information: %s", err) 224 | } 225 | 226 | if fi.IsDir() { 227 | // if a folder has been pushed 228 | ci, err = c.Data.StageFolder(ctx, ipfsRevProxyAddr, fName) 229 | if err != nil { 230 | return ci, fName, minerName, tok, jid, storagePrice, expiry, staged, fmt.Errorf("importing folder to hot storage (ipfs node): %s", err) 231 | } 232 | } else { 233 | // if a file has been pushed 234 | f, err := os.Open(fName) 235 | if err != nil { 236 | return ci, fName, minerName, tok, jid, storagePrice, expiry, staged, fmt.Errorf("importing file to hot storage (ipfs node): %s", err) 237 | } 238 | defer func() { 239 | e := f.Close() 240 | if e != nil { 241 | log.Warnf("closing file: %s\n", e) 242 | } 243 | }() 244 | 245 | res, err := c.Data.Stage(ctx, f) 246 | if err != nil { 247 | return ci, fName, minerName, tok, jid, storagePrice, expiry, staged, fmt.Errorf("importing file to hot storage (ipfs node): %s", err) 248 | } 249 | // json, err := protojson.MarshalOptions{Multiline: true, Indent: " ", EmitUnpopulated: true}.Marshal(res) 250 | // if err != nil { 251 | // return ci, fName, minerName, tok, jid, storagePrice, expiry, staged, fmt.Errorf("importing file to hot storage (ipfs node): %s", err) 252 | // } 253 | // ci = json["cid"] 254 | ci = res.Cid 255 | // ci = *ptrCid 256 | } 257 | 258 | staged = true 259 | 260 | log.Infof("[%d] Pushing %s to FFS...", id, ci) 261 | 262 | // TODO: tweak config 263 | cidConfig := &userPb.StorageConfig{ 264 | Repairable: false, 265 | Hot: &userPb.HotConfig{ 266 | Enabled: true, 267 | AllowUnfreeze: false, 268 | UnfreezeMaxPrice: 0, 269 | Ipfs: &userPb.IpfsConfig{ 270 | AddTimeout: 30, 271 | }, 272 | }, 273 | Cold: &userPb.ColdConfig{ 274 | Enabled: true, 275 | Filecoin: &userPb.FilConfig{ 276 | ReplicationFactor: 1, 277 | DealMinDuration: int64(minDealDuration), 278 | Address: addr, 279 | CountryCodes: nil, 280 | ExcludedMiners: nil, 281 | TrustedMiners: trustedMiners, 282 | Renew: &userPb.FilRenew{Enabled: false, Threshold: 0}, 283 | MaxPrice: uint64(storagePrice), 284 | FastRetrieval: false, 285 | DealStartOffset: 0, 286 | }, 287 | }, 288 | } 289 | 290 | applyRes, err := c.StorageConfig.Apply(ctx, ci, client.WithStorageConfig(cidConfig)) 291 | // jid = fmt.Sprintf("%s", jobID) 292 | jid = applyRes.JobId 293 | if err != nil { 294 | return ci, fName, minerName, tok, jid, storagePrice, expiry, staged, fmt.Errorf("pushing to FFS: %s", err) 295 | } 296 | 297 | log.Infof("[%d] Pushed successfully, queued job %s. Waiting for termination...", id, jid) 298 | 299 | return ci, fName, minerName, tok, jid, storagePrice, expiry, staged, nil 300 | } 301 | -------------------------------------------------------------------------------- /util/scripts.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "net/http" 7 | "os" 8 | "path/filepath" 9 | 10 | log "github.com/sirupsen/logrus" 11 | ) 12 | 13 | // WriteResponse writes some response for a given http request. 14 | func WriteResponse(data map[string]interface{}, w http.ResponseWriter) { 15 | jsonData, err := json.MarshalIndent(data, "", " ") 16 | if err != nil { 17 | fmt.Fprintln(w, data) 18 | log.Warn(err) 19 | return 20 | } 21 | fmt.Fprintln(w, string(jsonData)) 22 | return 23 | } 24 | 25 | // DirSize returns the size of a directory. 26 | func DirSize(path string) (uint64, error) { 27 | var size uint64 28 | err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error { 29 | if err != nil { 30 | return err 31 | } 32 | if !info.IsDir() { 33 | size += uint64(info.Size()) 34 | } 35 | return err 36 | }) 37 | return size, err 38 | } 39 | 40 | // Upload is a helper function 41 | func Upload(w http.ResponseWriter, r *http.Request) {} 42 | 43 | // RemoveContents removes unnecessary files from an asset directory. 44 | func RemoveContents(dir string) error { 45 | d, err := os.Open(dir) 46 | if err != nil { 47 | return err 48 | } 49 | defer d.Close() 50 | names, err := d.Readdirnames(-1) 51 | if err != nil { 52 | return err 53 | } 54 | for _, name := range names { 55 | if name != "random1080p.mp4" && name != "random720p.mp4" && name != "random360p.mp4" { 56 | err = os.RemoveAll(filepath.Join(dir, name)) 57 | if err != nil { 58 | return err 59 | } 60 | } 61 | } 62 | return nil 63 | } 64 | -------------------------------------------------------------------------------- /util/segment.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "os/exec" 5 | 6 | "github.com/google/uuid" 7 | ) 8 | 9 | // CreateSegments creates segments of a transcoded video using ffmpeg 10 | func CreateSegments(filename string, resolution string, id uuid.UUID) (bool, error) { 11 | success := false 12 | 13 | cmd := exec.Command( 14 | "ffmpeg", "-i", "./assets/"+id.String()+"/"+filename, 15 | "-profile:v", "baseline", "-level", "3.0", "-start_number", "0", 16 | "-hls_time", "5", "-hls_list_size", "0", "-f", "hls", 17 | "./assets/"+id.String()+"/"+resolution+"/myvid.m3u8") 18 | 19 | stdout, err := cmd.Output() 20 | if err == nil { 21 | success = true 22 | } 23 | _ = stdout 24 | if success == true { 25 | // cleanup 26 | exec.Command("rm", "-rf", "./assets/"+id.String()+"/"+filename).Output() 27 | } 28 | 29 | return success, err 30 | } 31 | --------------------------------------------------------------------------------