Upload 47 files
Browse filesFiles changed (47)
- app/.github/buildkit.tomlAdded+2
- app/.github/dependabot.ymlAdded+13
- app/.github/workflows/build.ymlAdded+43
- app/.github/workflows/goreleaser.ymlAdded+30
- app/.gitignoreAdded+30
- app/.goreleaser.yamlAdded+32
- app/.vscode/launch.jsonAdded+15
- app/DockerfileAdded+37
- app/LICENSEAdded+674
- app/README.mdAdded+159
- app/cache/bigcache.goAdded+99
- app/cache/cache.goAdded+72
- app/cache/cachutil.goAdded+63
- app/database/database.goAdded+77
- app/database/migrations/20230817172319_init.sqlAdded+66
- app/database/migrations/20230817172325_tables.sqlAdded+88
- app/database/migrations/20230817172329_functions.sqlAdded+188
- app/database/migrations/20230820014560_create_dirs_from_path.sqlAdded+48
- app/docker-compose.ymlAdded+33
- app/go.modAdded+74
- app/go.sumAdded+261
- app/haproxy.cfgAdded+24
- app/main.goAdded+64
- app/models/file.model.goAdded+41
- app/models/upload.model.goAdded+17
- app/models/user.model.goAdded+15
- app/public/demo.pngAdded
- app/routes/auth.goAdded+50
- app/routes/file.goAdded+107
- app/routes/main.goAdded+11
- app/routes/middleware.goAdded+46
- app/routes/upload.goAdded+55
- app/routes/user.goAdded+19
- app/schemas/common.goAdded+6
- app/schemas/file.schema.goAdded+78
- app/schemas/upload.schema.goAdded+21
- app/services/auth.service.goAdded+347
- app/services/file.service.goAdded+582
- app/services/upload.service.goAdded+167
- app/services/user.service.goAdded+91
- app/types/main.goAdded+43
- app/utils/auth/jwe.goAdded+62
- app/utils/config.goAdded+51
- app/utils/cron/cron.goAdded+72
- app/utils/logger.goAdded+19
- app/utils/main.goAdded+113
- app/utils/tgclient.goAdded+297
12[worker.oci] max-parallelism = 412345678910111213# To get started with Dependabot version updates, you'll need to specify which# package ecosystems to update and where the package manifests are located.# Please see the documentation for all configuration options:# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2updates: - package-ecosystem: "gomod" # See documentation for possible values directory: "/" # Location of package manifests schedule: interval: "daily" assignees: - "divyam234"12345678910111213141516171819202122232425262728293031323334353637383940414243name: Build App
on: workflow_dispatch: push: tags: - '*'env: DOCKER_BUILDKIT: 1 jobs: build_image: name: Build Image runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v3 with: fetch-depth: 0 - name: Install buildx uses: docker/setup-buildx-action@v2 with: config: .github/buildkit.toml
- name: Login to Docker uses: docker/login-action@v2 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }}
- name: Image Name id: imagename run: echo "name=ghcr.io/${GITHUB_REPOSITORY,,}/server" >> $GITHUB_OUTPUT
- name: Build Image uses: docker/build-push-action@v3 with: context: ./ platforms: linux/amd64,linux/arm64,linux/arm/v7 pull: true push: true tags: ${{ steps.imagename.outputs.name }}:latest123456789101112131415161718192021222324252627282930name: Goreleaser
on: push: tags: - "*"
permissions: contents: write
jobs: goreleaser: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v3 with: fetch-depth: 0 - name: Set up Go uses: actions/setup-go@v4 with: go-version: 1.21 - name: Run GoReleaser uses: goreleaser/goreleaser-action@v4 with: distribution: goreleaser version: latest args: release --clean env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}123456789101112131415161718192021222324252627282930# If you prefer the allow list template instead of the deny list, see community template:# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore## Binaries for programs and plugins*.exe*.exe~*.dll*.so*.dylib
# Test binary, built with `go test -c`*.test
# Output of the go coverage tool, specifically when used with LiteIDE*.out
# Dependency directories (remove the comment below to include it)# vendor/
# Go workspace filego.work
sessionscertssslcerts
*.env*.env.example*.env.local*.env.staging1234567891011121314151617181920212223242526272829303132project_name: teldriveenv: - GO111MODULE=onbuilds: - env: - CGO_ENABLED=0 flags: - -trimpath ldflags: - -s -w -extldflags "-static" - -X {{ .ModulePath }}/pkg/consts.Version={{ .Version }} - -X {{ .ModulePath }}/pkg/consts.Commit={{ .ShortCommit }} - -X {{ .ModulePath }}/pkg/consts.CommitDate={{ .CommitDate }} mod_timestamp: "{{ .CommitTimestamp }}" goos: - linux - windows - darwin goarch: - amd64 - arm - arm64checksum: name_template: "{{ .ProjectName }}_checksums.txt"archives: - name_template: "{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}" format_overrides: - goos: windows format: zip files: - README*.md - LICENSE123456789101112131415{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Launch Package", "type": "go", "request": "launch", "mode": "auto", "program": "main.go" } ]}12345678910111213141516171819202122232425262728293031323334353637FROM --platform=${BUILDPLATFORM:-linux/amd64} golang:alpine as builder
ARG TARGETPLATFORMARG BUILDPLATFORMARG TARGETOSARG TARGETARCH
RUN apk update && apk add --no-cache git ca-certificates tzdata && update-ca-certificates
WORKDIR /app
# use modulesCOPY go.mod .
ENV GO111MODULE=onRUN go mod download && go mod verify
COPY . .
RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build \ -ldflags='-w -s -extldflags "-static"' -a \ -o /app/teldrive .
FROM --platform=${TARGETPLATFORM:-linux/amd64} scratch
WORKDIR /app
COPY --from=builder /usr/share/zoneinfo /usr/share/zoneinfoCOPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=builder /app/teldrive /app/teldrive
EXPOSE 8080
ENTRYPOINT ["/app/teldrive"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license forsoftware and other kinds of works.
The licenses for most software and other practical works are designedto take away your freedom to share and change the works. By contrast,the GNU General Public License is intended to guarantee your freedom toshare and change all versions of a program--to make sure it remains freesoftware for all its users. We, the Free Software Foundation, use theGNU General Public License for most of our software; it applies also toany other work released this way by its authors. You can apply it toyour programs, too.
When we speak of free software, we are referring to freedom, notprice. Our General Public Licenses are designed to make sure that youhave the freedom to distribute copies of free software (and charge forthem if you wish), that you receive source code or can get it if youwant it, that you can change the software or use pieces of it in newfree programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying youthese rights or asking you to surrender the rights. Therefore, you havecertain responsibilities if you distribute copies of the software, or ifyou modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whethergratis or for a fee, you must pass on to the recipients the samefreedoms that you received. You must make sure that they, too, receiveor can get the source code. And you must show them these terms so theyknow their rights.
Developers that use the GNU GPL protect your rights with two steps:(1) assert copyright on the software, and (2) offer you this Licensegiving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explainsthat there is no warranty for this free software. For both users' andauthors' sake, the GPL requires that modified versions be marked aschanged, so that their problems will not be attributed erroneously toauthors of previous versions.
Some devices are designed to deny users access to install or runmodified versions of the software inside them, although the manufacturercan do so. This is fundamentally incompatible with the aim ofprotecting users' freedom to change the software. The systematicpattern of such abuse occurs in the area of products for individuals touse, which is precisely where it is most unacceptable. Therefore, wehave designed this version of the GPL to prohibit the practice for thoseproducts. If such problems arise substantially in other domains, westand ready to extend this provision to those domains in future versionsof the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.States should not allow patents to restrict development and use ofsoftware on general-purpose computers, but in those that do, we wish toavoid the special danger that patents applied to a free program couldmake it effectively proprietary. To prevent this, the GPL assures thatpatents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution andmodification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds ofworks, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under thisLicense. Each licensee is addressed as "you". "Licensees" and"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the workin a fashion requiring copyright permission, other than the making of anexact copy. The resulting work is called a "modified version" of theearlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work basedon the Program.
To "propagate" a work means to do anything with it that, withoutpermission, would make you directly or secondarily liable forinfringement under applicable copyright law, except executing it on acomputer or modifying a private copy. Propagation includes copying,distribution (with or without modification), making available to thepublic, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables otherparties to make or receive copies. Mere interaction with a user througha computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"to the extent that it includes a convenient and prominently visiblefeature that (1) displays an appropriate copyright notice, and (2)tells the user that there is no warranty for the work (except to theextent that warranties are provided), that licensees may convey thework under this License, and how to view a copy of this License. Ifthe interface presents a list of user commands or options, such as amenu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the workfor making modifications to it. "Object code" means any non-sourceform of a work.
A "Standard Interface" means an interface that either is an officialstandard defined by a recognized standards body, or, in the case ofinterfaces specified for a particular programming language, one thatis widely used among developers working in that language.
The "System Libraries" of an executable work include anything, otherthan the work as a whole, that (a) is included in the normal form ofpackaging a Major Component, but which is not part of that MajorComponent, and (b) serves only to enable use of the work with thatMajor Component, or to implement a Standard Interface for which animplementation is available to the public in source code form. A"Major Component", in this context, means a major essential component(kernel, window system, and so on) of the specific operating system(if any) on which the executable work runs, or a compiler used toproduce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means allthe source code needed to generate, install, and (for an executablework) run the object code and to modify the work, including scripts tocontrol those activities. However, it does not include the work'sSystem Libraries, or general-purpose tools or generally available freeprograms which are used unmodified in performing those activities butwhich are not part of the work. For example, Corresponding Sourceincludes interface definition files associated with source files forthe work, and the source code for shared libraries and dynamicallylinked subprograms that the work is specifically designed to require,such as by intimate data communication or control flow between thosesubprograms and other parts of the work.
The Corresponding Source need not include anything that userscan regenerate automatically from other parts of the CorrespondingSource.
The Corresponding Source for a work in source code form is thatsame work.
2. Basic Permissions.
All rights granted under this License are granted for the term ofcopyright on the Program, and are irrevocable provided the statedconditions are met. This License explicitly affirms your unlimitedpermission to run the unmodified Program. The output from running acovered work is covered by this License only if the output, given itscontent, constitutes a covered work. This License acknowledges yourrights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do notconvey, without conditions so long as your license otherwise remainsin force. You may convey covered works to others for the sole purposeof having them make modifications exclusively for you, or provide youwith facilities for running those works, provided that you comply withthe terms of this License in conveying all material for which you donot control copyright. Those thus making or running the covered worksfor you must do so exclusively on your behalf, under your directionand control, on terms that prohibit them from making any copies ofyour copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely underthe conditions stated below. Sublicensing is not allowed; section 10makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technologicalmeasure under any applicable law fulfilling obligations under article11 of the WIPO copyright treaty adopted on 20 December 1996, orsimilar laws prohibiting or restricting circumvention of suchmeasures.
When you convey a covered work, you waive any legal power to forbidcircumvention of technological measures to the extent such circumventionis effected by exercising rights under this License with respect tothe covered work, and you disclaim any intention to limit operation ormodification of the work as a means of enforcing, against the work'susers, your or third parties' legal rights to forbid circumvention oftechnological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as youreceive it, in any medium, provided that you conspicuously andappropriately publish on each copy an appropriate copyright notice;keep intact all notices stating that this License and anynon-permissive terms added in accord with section 7 apply to the code;keep intact all notices of the absence of any warranty; and give allrecipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications toproduce it from the Program, in the form of source code under theterms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independentworks, which are not by their nature extensions of the covered work,and which are not combined with it such as to form a larger program,in or on a volume of a storage or distribution medium, is called an"aggregate" if the compilation and its resulting copyright are notused to limit the access or legal rights of the compilation's usersbeyond what the individual works permit. Inclusion of a covered workin an aggregate does not cause this License to apply to the otherparts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the termsof sections 4 and 5, provided that you also convey themachine-readable Corresponding Source under the terms of this License,in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excludedfrom the Corresponding Source as a System Library, need not beincluded in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means anytangible personal property which is normally used for personal, family,or household purposes, or (2) anything designed or sold for incorporationinto a dwelling. In determining whether a product is a consumer product,doubtful cases shall be resolved in favor of coverage. For a particularproduct received by a particular user, "normally used" refers to atypical or common use of that class of product, regardless of the statusof the particular user or of the way in which the particular useractually uses, or expects or is expected to use, the product. A productis a consumer product regardless of whether the product has substantialcommercial, industrial or non-consumer uses, unless such uses representthe only significant mode of use of the product.
"Installation Information" for a User Product means any methods,procedures, authorization keys, or other information required to installand execute modified versions of a covered work in that User Product froma modified version of its Corresponding Source. The information mustsuffice to ensure that the continued functioning of the modified objectcode is in no case prevented or interfered with solely becausemodification has been made.
If you convey an object code work under this section in, or with, orspecifically for use in, a User Product, and the conveying occurs aspart of a transaction in which the right of possession and use of theUser Product is transferred to the recipient in perpetuity or for afixed term (regardless of how the transaction is characterized), theCorresponding Source conveyed under this section must be accompaniedby the Installation Information. But this requirement does not applyif neither you nor any third party retains the ability to installmodified object code on the User Product (for example, the work hasbeen installed in ROM).
The requirement to provide Installation Information does not include arequirement to continue to provide support service, warranty, or updatesfor a work that has been modified or installed by the recipient, or forthe User Product in which it has been modified or installed. Access to anetwork may be denied when the modification itself materially andadversely affects the operation of the network or violates the rules andprotocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,in accord with this section must be in a format that is publiclydocumented (and with an implementation available to the public insource code form), and must require no special password or key forunpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of thisLicense by making exceptions from one or more of its conditions.Additional permissions that are applicable to the entire Program shallbe treated as though they were included in this License, to the extentthat they are valid under applicable law. If additional permissionsapply only to part of the Program, that part may be used separatelyunder those permissions, but the entire Program remains governed bythis License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your optionremove any additional permissions from that copy, or from any part ofit. (Additional permissions may be written to require their ownremoval in certain cases when you modify the work.) You may placeadditional permissions on material, added by you to a covered work,for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material youadd to a covered work, you may (if authorized by the copyright holders ofthat material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "furtherrestrictions" within the meaning of section 10. If the Program as youreceived it, or any part of it, contains a notice stating that it isgoverned by this License along with a term that is a furtherrestriction, you may remove that term. If a license document containsa further restriction but permits relicensing or conveying under thisLicense, you may add to a covered work material governed by the termsof that license document, provided that the further restriction doesnot survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, youmust place, in the relevant source files, a statement of theadditional terms that apply to those files, or a notice indicatingwhere to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in theform of a separately written license, or stated as exceptions;the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expresslyprovided under this License. Any attempt otherwise to propagate ormodify it is void, and will automatically terminate your rights underthis License (including any patent licenses granted under the thirdparagraph of section 11).
However, if you cease all violation of this License, then yourlicense from a particular copyright holder is reinstated (a)provisionally, unless and until the copyright holder explicitly andfinally terminates your license, and (b) permanently, if the copyrightholder fails to notify you of the violation by some reasonable meansprior to 60 days after the cessation.
Moreover, your license from a particular copyright holder isreinstated permanently if the copyright holder notifies you of theviolation by some reasonable means, this is the first time you havereceived notice of violation of this License (for any work) from thatcopyright holder, and you cure the violation prior to 30 days afteryour receipt of the notice.
Termination of your rights under this section does not terminate thelicenses of parties who have received copies or rights from you underthis License. If your rights have been terminated and not permanentlyreinstated, you do not qualify to receive new licenses for the samematerial under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive orrun a copy of the Program. Ancillary propagation of a covered workoccurring solely as a consequence of using peer-to-peer transmissionto receive a copy likewise does not require acceptance. However,nothing other than this License grants you permission to propagate ormodify any covered work. These actions infringe copyright if you donot accept this License. Therefore, by modifying or propagating acovered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automaticallyreceives a license from the original licensors, to run, modify andpropagate that work, subject to this License. You are not responsiblefor enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of anorganization, or substantially all assets of one, or subdividing anorganization, or merging organizations. If propagation of a coveredwork results from an entity transaction, each party to thattransaction who receives a copy of the work also receives whateverlicenses to the work the party's predecessor in interest had or couldgive under the previous paragraph, plus a right to possession of theCorresponding Source of the work from the predecessor in interest, ifthe predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of therights granted or affirmed under this License. For example, you maynot impose a license fee, royalty, or other charge for exercise ofrights granted under this License, and you may not initiate litigation(including a cross-claim or counterclaim in a lawsuit) alleging thatany patent claim is infringed by making, using, selling, offering forsale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under thisLicense of the Program or a work on which the Program is based. Thework thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claimsowned or controlled by the contributor, whether already acquired orhereafter acquired, that would be infringed by some manner, permittedby this License, of making, using, or selling its contributor version,but do not include claims that would be infringed only as aconsequence of further modification of the contributor version. Forpurposes of this definition, "control" includes the right to grantpatent sublicenses in a manner consistent with the requirements ofthis License.
Each contributor grants you a non-exclusive, worldwide, royalty-freepatent license under the contributor's essential patent claims, tomake, use, sell, offer for sale, import and otherwise run, modify andpropagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any expressagreement or commitment, however denominated, not to enforce a patent(such as an express permission to practice a patent or covenant not tosue for patent infringement). To "grant" such a patent license to aparty means to make such an agreement or commitment not to enforce apatent against the party.
If you convey a covered work, knowingly relying on a patent license,and the Corresponding Source of the work is not available for anyoneto copy, free of charge and under the terms of this License, through apublicly available network server or other readily accessible means,then you must either (1) cause the Corresponding Source to be soavailable, or (2) arrange to deprive yourself of the benefit of thepatent license for this particular work, or (3) arrange, in a mannerconsistent with the requirements of this License, to extend the patentlicense to downstream recipients. "Knowingly relying" means you haveactual knowledge that, but for the patent license, your conveying thecovered work in a country, or your recipient's use of the covered workin a country, would infringe one or more identifiable patents in thatcountry that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction orarrangement, you convey, or propagate by procuring conveyance of, acovered work, and grant a patent license to some of the partiesreceiving the covered work authorizing them to use, propagate, modifyor convey a specific copy of the covered work, then the patent licenseyou grant is automatically extended to all recipients of the coveredwork and works based on it.
A patent license is "discriminatory" if it does not include withinthe scope of its coverage, prohibits the exercise of, or isconditioned on the non-exercise of one or more of the rights that arespecifically granted under this License. You may not convey a coveredwork if you are a party to an arrangement with a third party that isin the business of distributing software, under which you make paymentto the third party based on the extent of your activity of conveyingthe work, and under which the third party grants, to any of theparties who would receive the covered work from you, a discriminatorypatent license (a) in connection with copies of the covered workconveyed by you (or copies made from those copies), or (b) primarilyfor and in connection with specific products or compilations thatcontain the covered work, unless you entered into that arrangement,or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limitingany implied license or other defenses to infringement that mayotherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement orotherwise) that contradict the conditions of this License, they do notexcuse you from the conditions of this License. If you cannot convey acovered work so as to satisfy simultaneously your obligations under thisLicense and any other pertinent obligations, then as a consequence you maynot convey it at all. For example, if you agree to terms that obligate youto collect a royalty for further conveying from those to whom you conveythe Program, the only way you could satisfy both those terms and thisLicense would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you havepermission to link or combine any covered work with a work licensedunder version 3 of the GNU Affero General Public License into a singlecombined work, and to convey the resulting work. The terms of thisLicense will continue to apply to the part which is the covered work,but the special requirements of the GNU Affero General Public License,section 13, concerning interaction through a network will apply to thecombination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions ofthe GNU General Public License from time to time. Such new versions willbe similar in spirit to the present version, but may differ in detail toaddress new problems or concerns.
Each version is given a distinguishing version number. If theProgram specifies that a certain numbered version of the GNU GeneralPublic License "or any later version" applies to it, you have theoption of following the terms and conditions either of that numberedversion or of any later version published by the Free SoftwareFoundation. If the Program does not specify a version number of theGNU General Public License, you may choose any version ever publishedby the Free Software Foundation.
If the Program specifies that a proxy can decide which futureversions of the GNU General Public License can be used, that proxy'spublic statement of acceptance of a version permanently authorizes youto choose that version for the Program.
Later license versions may give you additional or differentpermissions. However, no additional obligations are imposed on anyauthor or copyright holder as a result of your choosing to follow alater version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BYAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHTHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTYOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULARPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAMIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OFALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITINGWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYSTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANYGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THEUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OFDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRDPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OFSUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability providedabove cannot be given local legal effect according to their terms,reviewing courts shall apply local law that most closely approximatesan absolute waiver of all civil liability in connection with theProgram, unless a warranty or assumption of liability accompanies acopy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatestpossible use to the public, the best way to achieve this is to make itfree software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safestto attach them to the start of each source file to most effectivelystate the exclusion of warranty; and each file should have at leastthe "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a shortnotice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriateparts of the General Public License. Of course, your program's commandsmight be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,if any, to sign a "copyright disclaimer" for the program, if necessary.For more information on this, and how to apply and follow the GNU GPL, see<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your programinto proprietary programs. If your program is a subroutine library, youmay consider it more useful to permit linking proprietary applications withthe library. If this is what you want to do, use the GNU Lesser GeneralPublic License instead of this License. But first, please read<https://www.gnu.org/licenses/why-not-lgpl.html>.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159<h1 align="center"> Fast Telegram Drive</h1>
[](https://discord.gg/hfTUKGU2C6)
<details open="open"> <summary>Table of Contents</summary> <ol> <li> <a href="#how-to-make-your-own">How to make your own</a> <ul> <li><a href="#deploy-using-docker-compose">Deploy using docker-compose</a></li> <li><a href="#deploy-without-docker-compose">Deploy without docker-compose</a></li> </ul> </li> <li><a href="#setting-up-things">Setting up things</a></li> <ul> <li><a href="#mandatory-vars">Mandatory Vars</a></li> <li><a href="#optional-vars">Optional Vars</a></li> </ul> </ol></details>
## Demo

[UI Repo ](https://github.com/divyam234/teldrive-ui)
### Deploy using docker-composeFirst clone the repository```shgit clone https://github.com/divyam234/teldrivecd teldrive```
**Follow Below Steps**
- Create the `.env` file with your variables and start your container.
```shdocker compose up -d```
- **Uploads from ui will be slower due to limitations of browser use [Teldrive Uploader](https://github.com/divyam234/teldrive-upload) for faster uploads.Make sure to use Multi Client mode if you are using uploader.**
- **If you want to share download links with others make sure to use multi client mode with bots otherwise it will not work.**
### Deploy without docker-composeFirst clone the repository```shgit clone https://github.com/divyam234/teldrive
```**Follow Below Steps**
- Fork UI Repo given above and Deploy it to Vercel or just use https://teldrive.vercel.app.- Download release binary of teldrive from releases section.- .env file will be same as mentioned above and additionally set variables mentioned below.As vercel app is hosted on https so we need local server also on https so that cookies works.```shellHTTPS=trueCOOKIE_SAME_SITE=false```- Generate https cert and key for localhost using mkcert and put these in sslcerts directory where executable is present.
- If you are using windows make sure to add cert as trusted using mkcert or manually.(You can see mkcert cli how to add that)
- Rename generated cert and key as cert.pem and key.pem respectively. - Make sure to add database migrations directory where where executable is present. - Now run the teldrive executable from releases.
- Finally change API URL from UI deployed on vercel to https://localhost:8080 in settings.
## Setting up things
If you're locally or remotely hosting, create a file named `.env` in the root directory and add all the variables there.An example of `.env` file:
```shAPP_ID=1234APP_HASH=abcCHANNEL_ID=1234HTTPS=falseCOOKIE_SAME_SITE=trueJWT_SECRET=abcDATABASE_URL=abcRATE_LIMIT=trueTG_CLIENT_DEVICE_MODEL="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36 Edg/115.0.1901.203" # Any valid browser user agent hereTG_CLIENT_SYSTEM_VERSION=Win32TG_CLIENT_APP_VERSION=2.1.9 KTG_CLIENT_LANG_CODE=enTG_CLIENT_SYSTEM_LANG_CODE=enTG_CLIENT_LANG_PACK=webkMULTI_CLIENT=falseMULTI_TOKEN1=55838383:yourfirstmulticlientbottokenhereMULTI_TOKEN2=55838383:yoursecondmulticlientbottokenhereMULTI_TOKEN3=55838383:yourthirdmulticlientbottokenhere```According to [Telegram TOS](https://core.telegram.org/api/obtaining_api_id#using-the-api-id): *all accounts that sign up or log in using unofficial Telegram API clients are automatically put under observation to avoid violations of the Terms of Service.So you can use APP_ID and APP_HASH from official K Telegram webclient from [here](https://github.com/morethanwords/tweb/blob/464bc4e76ff6417c7d996cca50c430d89d5d8175/src/config/app.ts#L36)*
**Use strong JWT secret instead of pure guessable string.You can use openssl to generate it.**
```bash$ openssl rand -base64 32```
**Multi Client Mode is recommended way to avoid flood errors and to enable max download speed if you are using downloaders like IDM and aria2c which use multiple connections to download files.**### Mandatory VarsBefore running the bot, you will need to set up the following mandatory variables:
- `APP_ID` : Use official ones as mentioned above.
- `APP_HASH` : Use official ones as mentioned above.
- `JWT_SECRET` : Used for signing jwt tokens
- `DATABASE_URL` : Connection String obtained from Postgres DB (you can use Neon db as free alternative fro postgres)
- `CHANNEL_ID` : This is the channel ID for the log channel where app will store files . To obtain a channel ID, create a new telegram channel (public or private), post something in the channel, forward the message to [@missrose_bot](https://telegram.dog/MissRose_bot) and **reply the forwarded message** with the /id command. Copy the forwarded channel ID and paste it into the this field.
### Optional VarsIn addition to the mandatory variables, you can also set the following optional variables:- `HTTPS` : Only needed when frontend is deployed on vercel.
- `COOKIE_SAME_SITE` : Only needed when frontend is deployed on vercel.- `MULTI_CLIENT` : Enable or Disable Multi Token mode. If true you have pass atleast one Multi Token- `MULTI_TOKEN[1....]` : Recommended to add atleast 10-12 tokens### For making use of Multi-Client support
> **Note**> What it multi-client feature and what it does? <br>> This feature shares the Telegram API requests between other bots to avoid getting floodwaited (A kind of rate limiting that Telegram does in the backend to avoid flooding their servers) and to make the server handle more requests. <br>
To enable multi-client, generate new bot tokens and add it as your environmental variables with the following key names.
`MULTI_TOKEN1`: Add your first bot token here.
`MULTI_TOKEN2`: Add your second bot token here.
you may also add as many as bots you want. (max limit is not tested yet)`MULTI_TOKEN3`, `MULTI_TOKEN4`, etc.
> **Warning**> Don't forget to add all these bots to the `CHANNEL_ID` as admin for the proper functioning
## FAQ
- How to get Postgres DB url ?> You can spin up local postgres instance but its not recommended as there is lot of hassle in backup and transfering data.Recommended way is to use any free cloud postgres DB.I will recommend to use [Neon DB](https://neon.tech/).
## Contributing
Feel free to contribute to this project if you have any further ideas.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899package cache
import ( "bytes" "context" "encoding/gob" "errors"
"github.com/allegro/bigcache/v3")
type bigCache struct { cache *bigcache.BigCache}
func newBigCache(cacheConfig *cacheConfig) (*bigCache, error) { cache, err := bigcache.New(context.Background(), bigcache.Config{ Shards: 16, LifeWindow: cacheConfig.ttl, CleanWindow: cacheConfig.cleanFreq, MaxEntriesInWindow: 1000 * 10 * 60, MaxEntrySize: 500, Verbose: false, HardMaxCacheSize: cacheConfig.size, StatsEnabled: true, }) if err != nil { return nil, err } return &bigCache{ cache: cache, }, nil}
// Set inserts the key/value pair into the cache.// Only the exported fields of the given struct will be// serialized and storedfunc (c *bigCache) Set(key, value interface{}) error { keyString, ok := key.(string) if !ok { return errors.New("a cache key must be a string") }
valueBytes, err := serializeGOB(value) if err != nil { return err }
return c.cache.Set(keyString, valueBytes)}
// Get returns the value correlating to the key in the cachefunc (c *bigCache) Get(key interface{}) (interface{}, error) { // Assert the key is of string type keyString, ok := key.(string) if !ok { return nil, errors.New("a cache key must be a string") }
// Get the value in the byte format it is stored in valueBytes, err := c.cache.Get(keyString) if err != nil { return nil, err }
// Deserialize the bytes of the value value, err := deserializeGOB(valueBytes) if err != nil { return nil, err }
return value, nil}
func serializeGOB(value interface{}) ([]byte, error) { buf := bytes.Buffer{} enc := gob.NewEncoder(&buf) gob.Register(value)
err := enc.Encode(&value) if err != nil { return nil, err }
return buf.Bytes(), nil}
func deserializeGOB(valueBytes []byte) (interface{}, error) { var value interface{} buf := bytes.NewBuffer(valueBytes) dec := gob.NewDecoder(buf)
err := dec.Decode(&value) if err != nil { return nil, err }
return value, nil}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172package cache
import ( "time")
type cacheConfig struct { size int // Size in MB ttl time.Duration cleanFreq time.Duration}
// Interface to wrap any caching implementationtype Cache interface { Set(key, value interface{}) error // Only exported fields in struct will be stored Get(key interface{}) (interface{}, error)}
// New builds a new default cache. You may pass options to modify the default valuesfunc New(opts ...Option) (Cache, error) { cacheConfig := &cacheConfig{ size: 1, ttl: 60 * time.Second, cleanFreq: 30 * time.Second, }
for _, opt := range opts { opt.apply(cacheConfig) }
cache, err := newBigCache(cacheConfig) if err != nil { return nil, err } return cache, nil}
type Option interface { apply(cacheConfig *cacheConfig)}
type optionFunc func(*cacheConfig)
func (opt optionFunc) apply(cacheConfig *cacheConfig) { opt(cacheConfig)}
// WithSizeInMB sets the size of the cache in MBs// The minimum size of the cache is 1 MB// If a size of 0 or less is passed the cache will have unlimited sizefunc WithSizeInMB(size int) Option { return optionFunc(func(cacheConfig *cacheConfig) { cacheConfig.size = size })}
// WithTTL will cause the cache to expire any item that lives longer// than the given ttlfunc WithTTL(ttl time.Duration) Option { return optionFunc(func(cacheConfig *cacheConfig) { cacheConfig.ttl = ttl })}
// WithCleanFrequency sets how often the cache will clean out expired items// The lowest the frequency may be is 1 second// If the time is 0 then no cleaning will happen and items will never be removedfunc WithCleanFrequency(cleanFreq time.Duration) Option { return optionFunc(func(cacheConfig *cacheConfig) { cacheConfig.cleanFreq = cleanFreq })}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263package cache
import ( "reflect" "time")
var globalCache Cache
func CacheInit() {
var err error globalCache, err = New( WithSizeInMB(10), WithTTL(12*time.Hour), WithCleanFrequency(24*time.Hour), ) if err != nil { panic("Failed to initialize global cache: " + err.Error()) }}
func GetCache() Cache { return globalCache}
func CachedFunction(fn interface{}, key string) func(...interface{}) (interface{}, error) { return func(args ...interface{}) (interface{}, error) {
// Check if the result is already cached if cachedResult, err := globalCache.Get(key); err == nil { return cachedResult, nil }
// If not cached, call the original function to get the result f := reflect.ValueOf(fn) if len(args) == 0 { args = nil // Ensure nil is passed when there are no arguments. } result := f.Call(getArgs(args))
// Check if the function returned an error as the last return value if err, ok := result[len(result)-1].Interface().(error); ok && err != nil { return nil, err }
// Extract the result from the function call finalResult := result[0].Interface()
// Cache the result with a default TTL (time-to-live) globalCache.Set(key, finalResult)
return finalResult, nil }}
func getArgs(args []interface{}) []reflect.Value { var values []reflect.Value for _, arg := range args { values = append(values, reflect.ValueOf(arg)) } return values}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677package database
import ( "log" "os" "path/filepath" "time"
"github.com/divyam234/teldrive/utils" "github.com/pressly/goose/v3" "gorm.io/driver/postgres" "gorm.io/gorm" "gorm.io/gorm/logger" "gorm.io/gorm/schema")
var DB *gorm.DB
func InitDB() {
var err error
newLogger := logger.New( log.New(os.Stdout, "\r\n", log.LstdFlags), logger.Config{ SlowThreshold: time.Second, LogLevel: logger.Silent, IgnoreRecordNotFoundError: true, ParameterizedQueries: true, Colorful: false, }, )
DB, err = gorm.Open(postgres.Open(utils.GetConfig().DatabaseUrl), &gorm.Config{ NamingStrategy: schema.NamingStrategy{ TablePrefix: "teldrive.", SingularTable: false, }, PrepareStmt: false, NowFunc: func() time.Time { return time.Now().UTC() }, Logger: newLogger, }) if err != nil { panic(err) }
sqlDB, err := DB.DB() if err != nil { panic(err) } sqlDB.SetMaxIdleConns(10) sqlDB.SetMaxOpenConns(100)
sqlDB.SetConnMaxLifetime(time.Hour) go func() { DB.Exec(`create collation if not exists numeric (provider = icu, locale = 'en@colnumeric=yes');`) if utils.GetConfig().RunMigrations { migrate() } }()
}
func migrate() {
config := utils.GetConfig()
if err := goose.SetDialect("postgres"); err != nil { panic(err) } db, _ := DB.DB() if err := goose.Up(db, filepath.Join(config.ExecDir, "database", "migrations")); err != nil { panic(err) }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566-- +goose Upcreate extension if not exists pgcrypto;
create extension if not exists btree_gin;
create schema if not exists teldrive;
create collation if not exists numeric (provider = icu, locale = 'en@colnumeric=yes');
-- +goose StatementBegincreate or replacefunction teldrive.generate_uid(size int) returns text language plpgsql as $$declare characters text := 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
bytes bytea := gen_random_bytes(size);
l int := length(characters);
i int := 0;
output text := '';
begin while i < size loop output := output || substr(characters,get_byte(bytes,i) % l + 1,1);
i := i + 1;end loop;
return output;end;
$$;-- +goose StatementEnd
-- +goose StatementBegincreate or replacefunction teldrive.get_tsvector(t text) returns tsvector language plpgsql immutable as $$declare res tsvector := to_tsvector(regexp_replace(t,'[^A-Za-z0-9 ]',' ','g'));
begin return res;end;
$$;-- +goose StatementEnd
-- +goose StatementBegincreate or replacefunction teldrive.get_tsquery(t text) returns tsquery language plpgsql immutable as $$declare res tsquery = concat(plainto_tsquery(regexp_replace(t,'[^A-Za-z0-9 ]',' ','g')),':*')::tsquery;
begin return res;end;
$$;-- +goose StatementEnd12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788-- +goose Upcreate table teldrive.files (id text primary key not null default teldrive.generate_uid(16),name text not null,type text not null,mime_type text not null,path text null,size bigint null,starred bool not null,depth integer null,user_id bigint not null,parent_id text null,status text default 'active'::text,channel_id bigint null,parts jsonb null,created_at timestamp not null default timezone('utc'::text,now()),updated_at timestamp not null default timezone('utc'::text,now()),constraint unique_file unique (name,parent_id,user_id));
create table teldrive.uploads ( id text not null primary key default teldrive.generate_uid(16), upload_id text not null, name text not null, part_no int4 not null, part_id int4 not null, total_parts int4 not null, channel_id int8 not null, size int8 not null, created_at timestamp null default timezone('utc'::text,now()));
create table teldrive.users ( user_id bigint not null primary key, name text null, user_name text null, is_premium bool not null, tg_session text not null, settings jsonb null, created_at timestamptz not null default timezone('utc'::text,now()), updated_at timestamptz not null default timezone('utc'::text,now()));
create collation if not exists numeric (provider = icu, locale = 'en@colnumeric=yes');create index name_search_idx onteldrive.files using gin (teldrive.get_tsvector(name),updated_at);
create index name_numeric_idx onteldrive.files(name collate numeric nulls first);
create index parent_name_numeric_idx onteldrive.files (parent_id,name collate numeric desc);
create index path_idx onteldrive.files (path);
create index parent_idx onteldrive.files (parent_id);
create index starred_updated_at_idx onteldrive.files (starred,updated_at desc);
create index status_idx on teldrive.files (status);
create index user_id_idx on teldrive.files (user_id);
-- +goose Downdrop table if exists teldrive.files;drop table if exists teldrive.uploads;drop table if exists teldrive.users;drop index if exists teldrive.name_search_idx;drop index if exists teldrive.name_numeric_idx;drop index if exists teldrive.parent_name_numeric_idx;drop index if exists teldrive.path_idx;drop index if exists teldrive.parent_idx;drop index if exists teldrive.starred_updated_at_idx;drop index if exists teldrive.status_idx;drop index if exists teldrive.user_id_idx;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188-- +goose Up
-- +goose StatementBegincreate procedure teldrive.update_size() language plpgsql as $$declare rec record;
total_size bigint;
begin
for rec inselect idfrom fileswhere type = 'folder'order by depth desc loop total_size := ( select sum(size) as total_size from teldrive.files where parent_id = rec.id);
update teldrive.filesset size = total_sizewhere id = rec.id;end loop;end;
$$;-- +goose StatementEnd
-- +goose StatementBegincreate function teldrive.update_folder(folder_id text,new_name text default null,new_path text default null) returns setof teldrive.files language plpgsqlas $$declare folder record;
path_items text [];
begin
if new_path is null thenselect *into folderfrom teldrive.fileswhere id = folder_id;
path_items := string_to_array(folder.path,'/');
path_items [array_length(path_items,1)] := new_name;
new_path := array_to_string(path_items,'/');end if;
update teldrive.filesset path = new_path, name = new_namewhere id = folder_id;
for folder inselect *from teldrive.fileswhere type = 'folder' and parent_id = folder_id loop call teldrive.update_folder( folder.id, folder.name, concat(new_path, '/', folder.name));end loop;
return queryselect *from teldrive.fileswhere id = folder_id;end;
$$;-- +goose StatementEnd
-- +goose StatementBegincreate procedure teldrive.delete_files(in file_ids text[],in op text default 'bulk') language plpgsqlas $$ declare rec record;
begin if op = 'bulk' then for rec inselect id, typefrom teldrive.fileswhere id = any (file_ids) loop if rec.type = 'folder' then call teldrive.delete_files(array [rec.id], 'single');
deletefrom teldrive.fileswhere id = rec.id;else update teldrive.filesset status = 'pending_deletion'where id = rec.id;end if;end loop;else for rec inselect id, typefrom teldrive.fileswhere parent_id = file_ids[1] loop if rec.type = 'folder' then call teldrive.delete_files(array [rec.id], 'single');
deletefrom teldrive.fileswhere id = rec.id;else update teldrive.filesset status = 'pending_deletion'where id = rec.id;end if;end loop;end if;end;
$$;-- +goose StatementEnd
-- +goose Downdrop procedure if exists teldrive.update_size;drop function if exists teldrive.update_folder;drop procedure if exists teldrive.delete_files;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748-- +goose Up-- +goose StatementBegin
CREATE OR REPLACE FUNCTION teldrive.create_directories( IN tg_id BIGINT, IN long_path TEXT) RETURNS SETOF teldrive.files AS $$DECLARE path_parts TEXT[]; current_directory_id TEXT; new_directory_id TEXT; directory_name TEXT; path_so_far TEXT; depth_dir integer;begin path_parts := string_to_array(regexp_replace(long_path, '^/+', ''), '/'); path_so_far := ''; depth_dir := 0;
SELECT id into current_directory_id FROM teldrive.files WHERE parent_id='root';
FOR directory_name IN SELECT unnest(path_parts) LOOP path_so_far := CONCAT(path_so_far,'/', directory_name); depth_dir := depth_dir +1; SELECT id INTO new_directory_id FROM teldrive.files WHERE parent_id = current_directory_id AND "name" = directory_name AND "user_id"=tg_id;
IF new_directory_id IS NULL THEN INSERT INTO teldrive.files ("name", "type", mime_type, parent_id, "user_id",starred,"depth","path") VALUES (directory_name, 'folder', 'drive/folder', current_directory_id, tg_id,false,depth_dir,path_so_far) RETURNING id INTO new_directory_id; END IF; current_directory_id := new_directory_id; END LOOP;
RETURN QUERY SELECT * FROM teldrive.files WHERE id = current_directory_id;END;$$ LANGUAGE plpgsql;-- +goose StatementEnd
-- +goose DownDROP FUNCTION IF EXISTS teldrive.create_directories;123456789101112131415161718192021222324252627282930313233version: "3.8"
services: server: image: ghcr.io/divyam234/teldrive/server:latest restart: always container_name: server volumes: - ./sessions:/app/sessions:rw - ./database:/app/database env_file: .env ports: - 8080
client: image: ghcr.io/divyam234/teldrive/client:latest restart: always container_name: client ports: - 3000 haproxy: image: haproxy:latest volumes: - ./haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg # ports: # - 80:80 # - 443:443 ports: - 8000:8000 depends_on: - server - client1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374module github.com/divyam234/teldrive
go 1.21
require ( github.com/allegro/bigcache/v3 v3.1.0 github.com/divyam234/cors v1.4.2 github.com/gin-gonic/gin v1.9.1 github.com/go-co-op/gocron v1.31.1 github.com/go-jose/go-jose/v3 v3.0.0 github.com/gotd/contrib v0.19.0 github.com/gotd/td v0.84.0 github.com/joho/godotenv v1.5.1 github.com/kelseyhightower/envconfig v1.4.0 github.com/mitchellh/mapstructure v1.5.0 github.com/pkg/errors v0.9.1 github.com/quantumsheep/range-parser v1.1.0 go.uber.org/zap v1.25.0 golang.org/x/exp v0.0.0-20230811145659-89c5cff77bcb golang.org/x/time v0.3.0 gorm.io/driver/postgres v1.5.2 gorm.io/gorm v1.25.2)
require github.com/robfig/cron/v3 v3.0.1 // indirect
require ( github.com/bytedance/sonic v1.9.1 // indirect github.com/cenkalti/backoff/v4 v4.2.1 github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect github.com/gabriel-vasile/mimetype v1.4.2 // indirect github.com/gin-contrib/sse v0.1.0 // indirect github.com/go-faster/errors v0.6.1 // indirect github.com/go-faster/jx v1.0.1 // indirect github.com/go-faster/xor v1.0.0 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/validator/v10 v10.14.0 // indirect github.com/goccy/go-json v0.10.2 // indirect github.com/gorilla/websocket v1.5.0 github.com/gotd/ige v0.2.2 // indirect github.com/gotd/neo v0.1.5 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect github.com/jackc/pgx/v5 v5.4.3 github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/now v1.1.5 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/compress v1.16.7 // indirect github.com/klauspost/cpuid/v2 v2.2.4 // indirect github.com/leodido/go-urn v1.2.4 // indirect github.com/mattn/go-isatty v0.0.19 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/pelletier/go-toml/v2 v2.0.8 // indirect github.com/pressly/goose/v3 v3.15.0 github.com/segmentio/asm v1.2.0 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.2.11 // indirect go.opentelemetry.io/otel v1.16.0 // indirect go.opentelemetry.io/otel/trace v1.16.0 // indirect go.uber.org/atomic v1.11.0 // indirect go.uber.org/multierr v1.11.0 // indirect golang.org/x/arch v0.3.0 // indirect golang.org/x/crypto v0.11.0 // indirect golang.org/x/net v0.12.0 // indirect golang.org/x/sync v0.3.0 // indirect golang.org/x/sys v0.10.0 // indirect golang.org/x/text v0.11.0 // indirect google.golang.org/protobuf v1.30.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect nhooyr.io/websocket v1.8.7 // indirect rsc.io/qr v0.2.0 // indirect)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261github.com/allegro/bigcache/v3 v3.1.0 h1:H2Vp8VOvxcrB91o86fUSVJFqeuz8kpyyB02eH3bSzwk=github.com/allegro/bigcache/v3 v3.1.0/go.mod h1:aPyh7jEvrog9zAwx5N7+JUQX5dZTSGpxF1LAR4dr35I=github.com/benbjohnson/clock v1.3.0 h1:ip6w0uFQkncKQ979AypyG0ER7mqUSBdKLOgAle/AT8A=github.com/benbjohnson/clock v1.3.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s=github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U=github.com/cenkalti/backoff/v4 v4.2.1 h1:y4OZtCnogmCPw98Zjyt5a6+QwPLGkiQsYW5oUqylYbM=github.com/cenkalti/backoff/v4 v4.2.1/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams=github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/divyam234/cors v1.4.2 h1:moAxStmYpvG9/SkPz+Wld02iutgo3JcUvrez6Kit/D8=github.com/divyam234/cors v1.4.2/go.mod h1:JrxBJAqTU7jtPItodwf2mzxbbZm0Qq0NFkK8jo9UUDk=github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M=github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=github.com/go-co-op/gocron v1.31.1 h1:LZAuBlU0t3SPGUMJGhrJ6VuCc3CsrYzkzicygvVWlfA=github.com/go-co-op/gocron v1.31.1/go.mod h1:39f6KNSGVOU1LO/ZOoZfcSxwlsJDQOKSu8erN0SH48Y=github.com/go-faster/errors v0.6.1 h1:nNIPOBkprlKzkThvS/0YaX8Zs9KewLCOSFQS5BU06FI=github.com/go-faster/errors v0.6.1/go.mod h1:5MGV2/2T9yvlrbhe9pD9LO5Z/2zCSq2T8j+Jpi2LAyY=github.com/go-faster/jx v1.0.1 h1:NhSJEZtqj6KmXf63On7Hg7/sjUX+gotSc/eM6bZCZ00=github.com/go-faster/jx v1.0.1/go.mod h1:vKDNikrKoyUmpzaJ0OkIkRQClNHFX/nF3dnTJZb3skg=github.com/go-faster/xor v0.3.0/go.mod h1:x5CaDY9UKErKzqfRfFZdfu+OSTfoZny3w5Ak7UxcipQ=github.com/go-faster/xor v1.0.0 h1:2o8vTOgErSGHP3/7XwA5ib1FTtUsNtwCoLLBjl31X38=github.com/go-faster/xor v1.0.0/go.mod h1:x5CaDY9UKErKzqfRfFZdfu+OSTfoZny3w5Ak7UxcipQ=github.com/go-jose/go-jose/v3 v3.0.0 h1:s6rrhirfEP/CGIoc6p+PZAeogN2SxKav6Wp7+dyMWVo=github.com/go-jose/go-jose/v3 v3.0.0/go.mod h1:RNkWWRld676jZEYoV3+XK8L2ZnNSvIsxFMht0mSX+u8=github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8=github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA=github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI=github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js=github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee h1:s+21KNqlpePfkah2I+gwHF8xmJWRjooY+5248k6m4A0=github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22YWvt/FAX9NnzrNzcI4wNYi9Yku4O0LKYflo=github.com/gobwas/pool v0.2.0 h1:QEmUOlnSjWtnpRGHF3SauEiOsy82Cup83Vf2LcMlnc8=github.com/gobwas/pool v0.2.0/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=github.com/gobwas/ws v1.0.2 h1:CoAavW/wd/kulfZmSIBt6p24n4j7tHgNVCjsfHVNUbo=github.com/gobwas/ws v1.0.2/go.mod h1:szmBTxLgaFppYjEmNtny/v3w89xOydFnnZMcgRRu/EM=github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk=github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=github.com/gotd/contrib v0.19.0 h1:O6GvMrRVeFslIHLUcpaHVzcl9/5PcgR2jQTIIeTyds0=github.com/gotd/contrib v0.19.0/go.mod h1:LzPxzRF0FvtpBt/WyODWQnPpk0tm/G9z6RHUoPqMakU=github.com/gotd/ige v0.2.2 h1:XQ9dJZwBfDnOGSTxKXBGP4gMud3Qku2ekScRjDWWfEk=github.com/gotd/ige v0.2.2/go.mod h1:tuCRb+Y5Y3eNTo3ypIfNpQ4MFjrnONiL2jN2AKZXmb0=github.com/gotd/neo v0.1.5 h1:oj0iQfMbGClP8xI59x7fE/uHoTJD7NZH9oV1WNuPukQ=github.com/gotd/neo v0.1.5/go.mod h1:9A2a4bn9zL6FADufBdt7tZt+WMhvZoc5gWXihOPoiBQ=github.com/gotd/td v0.84.0 h1:oWMp5HczCAFSgKWgWFCuYjELBgcRVcRpGLdQ1bP2kpg=github.com/gotd/td v0.84.0/go.mod h1:3dQsGL9rxMcS1Z9Na3S7U8e/pLMzbLIT2jM3E5IuUk0=github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=github.com/jackc/pgx/v5 v5.4.3 h1:cxFyXhxlvAifxnkKKdlxv8XqUf59tDlYjnV5YYfsJJY=github.com/jackc/pgx/v5 v5.4.3/go.mod h1:Ig06C2Vu0t5qXC60W8sqIthScaEnFvojjj9dSljmHRA=github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs=github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8=github.com/kelseyhightower/envconfig v1.4.0 h1:Im6hONhd3pLkfDFsbRgu68RDNkGF1r3dvMUtDTo2cv8=github.com/kelseyhightower/envconfig v1.4.0/go.mod h1:cccZRl6mQpaq41TPp5QxidR+Sa3axMbJDNb//FQX6Gg=github.com/klauspost/compress v1.10.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=github.com/klauspost/compress v1.16.7 h1:2mk3MPGNzKyxErAw8YaohYh69+pa4sIQSC0fPGCFR9I=github.com/klauspost/compress v1.16.7/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk=github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY=github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII=github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ=github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4=github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=github.com/pressly/goose/v3 v3.15.0 h1:6tY5aDqFknY6VZkorFGgZtWygodZQxfmmEF4rqyJW9k=github.com/pressly/goose/v3 v3.15.0/go.mod h1:LlIo3zGccjb/YUgG+Svdb9Er14vefRdlDI7URCDrwYo=github.com/quantumsheep/range-parser v1.1.0 h1:k4f1F58f8FF54FBYc9dYBRM+8JkAxFo11gC3IeMH4rU=github.com/quantumsheep/range-parser v1.1.0/go.mod h1:acv4Vt2PvpGvRsvGju7Gk2ahKluZJsIUNR69W53J22I=github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o=github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M=github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=github.com/segmentio/asm v1.2.0 h1:9BQrFxC+YOHJlTlHGkTrFWf59nbL3XnCoFLTwDCI7ys=github.com/segmentio/asm v1.2.0/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs=github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY=github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=go.opentelemetry.io/otel v1.16.0 h1:Z7GVAX/UkAXPKsy94IU+i6thsQS4nb7LviLpnaNeW8s=go.opentelemetry.io/otel v1.16.0/go.mod h1:vl0h9NUa1D5s1nv3A5vZOYWn8av4K8Ml6JDeHrT/bx4=go.opentelemetry.io/otel/trace v1.16.0 h1:8JRpaObFoW0pxuVPapkgH8UhHQj+bJW8jJsCZEu5MQs=go.opentelemetry.io/otel/trace v1.16.0/go.mod h1:Yt9vYq1SdNz3xdjZZK7wcXv1qv2pwLkqr2QVwea0ef0=go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=go.uber.org/goleak v1.2.0 h1:xqgm/S+aQvhWFTtR0XK3Jvg7z8kGV8P4X14IzwN3Eqk=go.uber.org/goleak v1.2.0/go.mod h1:XJYK+MuIchqpmGmUSAzotztawfKvYLUIgg7guXrwVUo=go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=go.uber.org/zap v1.25.0 h1:4Hvk6GtkucQ790dqmj7l1eEnRdKm3k3ZUrUMS2d5+5c=go.uber.org/zap v1.25.0/go.mod h1:JIAUzQIH94IC4fOJQm7gMmBJP5k7wQfdcnYdPoEXJYk=golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k=golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=golang.org/x/crypto v0.0.0-20190911031432-227b76d455e7/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=golang.org/x/crypto v0.11.0 h1:6Ewdq3tDic1mg5xRO4milcWCfMVQhI4NkqWWvqejpuA=golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio=golang.org/x/exp v0.0.0-20230811145659-89c5cff77bcb h1:mIKbk8weKhSeLH2GmUTrvx8CjkyJmnU1wFmg59CUjFA=golang.org/x/exp v0.0.0-20230811145659-89c5cff77bcb/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc=golang.org/x/mod v0.12.0 h1:rmsUpXtvNzj340zd98LZ4KntptpfRHwpFOHG188oHXc=golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=golang.org/x/net v0.12.0 h1:cfawfvKITfUsFCeJIHJrbSxpeu/E81khclypR0GVT50=golang.org/x/net v0.12.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA=golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=golang.org/x/sync v0.3.0 h1:ftCYgMx6zT/asHUrPw8BLLscYtGznsLAnjq5RH9P66E=golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA=golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=golang.org/x/text v0.11.0 h1:LAntKIrcmeSKERyiOh0XMV39LXS8IE9UL2yP7+f5ij4=golang.org/x/text v0.11.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4=golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=golang.org/x/tools v0.11.0 h1:EMCa6U9S2LtZXLAMoWiR/R8dAQFRqbAitmbJ2UKhoi8=golang.org/x/tools v0.11.0/go.mod h1:anzJrxPjNtfgiYQYirP2CPGzGLxrH2u2QBhn6Bf3qY8=golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng=google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=gorm.io/driver/postgres v1.5.2 h1:ytTDxxEv+MplXOfFe3Lzm7SjG09fcdb3Z/c056DTBx0=gorm.io/driver/postgres v1.5.2/go.mod h1:fmpX0m2I1PKuR7mKZiEluwrP3hbs+ps7JIGMUBpCgl8=gorm.io/gorm v1.25.2 h1:gs1o6Vsa+oVKG/a9ElL3XgyGfghFfkKA2SInQaCyMho=gorm.io/gorm v1.25.2/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k=lukechampine.com/uint128 v1.3.0 h1:cDdUVfRwDUDovz610ABgFD17nXD4/uDgVHl2sC3+sbo=lukechampine.com/uint128 v1.3.0/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk=modernc.org/cc/v3 v3.41.0 h1:QoR1Sn3YWlmA1T4vLaKZfawdVtSiGx8H+cEojbC7v1Q=modernc.org/cc/v3 v3.41.0/go.mod h1:Ni4zjJYJ04CDOhG7dn640WGfwBzfE0ecX8TyMB0Fv0Y=modernc.org/ccgo/v3 v3.16.14 h1:af6KNtFgsVmnDYrWk3PQCS9XT6BXe7o3ZFJKkIKvXNQ=modernc.org/ccgo/v3 v3.16.14/go.mod h1:mPDSujUIaTNWQSG4eqKw+atqLOEbma6Ncsa94WbC9zo=modernc.org/libc v1.24.1 h1:uvJSeCKL/AgzBo2yYIPPTy82v21KgGnizcGYfBHaNuM=modernc.org/libc v1.24.1/go.mod h1:FmfO1RLrU3MHJfyi9eYYmZBfi/R+tqZ6+hQ3yQQUkak=modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4=modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo=modernc.org/memory v1.6.0 h1:i6mzavxrE9a30whzMfwf7XWVODx2r5OYXvU46cirX7o=modernc.org/memory v1.6.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU=modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4=modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0=modernc.org/sqlite v1.25.0 h1:AFweiwPNd/b3BoKnBOfFm+Y260guGMF+0UFk0savqeA=modernc.org/sqlite v1.25.0/go.mod h1:FL3pVXie73rg3Rii6V/u5BoHlSoyeZeIgKZEgHARyCU=modernc.org/strutil v1.1.3 h1:fNMm+oJklMGYfU9Ylcywl0CO5O6nTfaowNsh2wpPjzY=modernc.org/strutil v1.1.3/go.mod h1:MEHNA7PdEnEwLvspRMtWTNnp2nnyvMfkimT1NKNAGbw=modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=nhooyr.io/websocket v1.8.7 h1:usjR2uOr/zjjkVMy0lW+PPohFok7PCow5sDjLgX4P4g=nhooyr.io/websocket v1.8.7/go.mod h1:B70DZP8IakI65RVQ51MsWP/8jndNma26DVA/nFSCgW0=rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=rsc.io/qr v0.2.0 h1:6vBLea5/NRMVTz8V66gipeLycZMl/+UlFmk8DvqQ6WY=rsc.io/qr v0.2.0/go.mod h1:IF+uZjkb9fqyeF/4tlBoynqmQxUoPfWEKh921coOuXs=123456789101112131415161718192021222324# global# tune.h2.initial-window-size 1048576# tune.h2.max-concurrent-streams 1000
defaults mode http log global
frontend http-in # bind *:80 # bind *:443 ssl crt /etc/ssl/fullchain.pem alpn h2,http/1.1 bind *:8000 mode http acl is_api path_beg /api use_backend api-backend if is_api default_backend frontend
backend api-backend balance roundrobin server go-backend server:8080 check
backend frontend balance roundrobin server nextjs-frontend client:3000 check12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364package main
import ( "fmt" "path/filepath" "time"
"github.com/divyam234/teldrive/cache" "github.com/divyam234/teldrive/database" "github.com/divyam234/teldrive/routes" "github.com/divyam234/teldrive/utils"
"github.com/divyam234/cors" "github.com/divyam234/teldrive/utils/cron" "github.com/gin-gonic/gin" "github.com/go-co-op/gocron")
func main() {
gin.SetMode(gin.ReleaseMode)
router := gin.Default()
utils.InitConfig()
utils.InitializeLogger()
database.InitDB()
cache.CacheInit()
utils.InitBotClients()
cron.FilesDeleteJob()
scheduler := gocron.NewScheduler(time.UTC)
scheduler.Every(1).Hours().Do(cron.FilesDeleteJob)
router.Use(cors.New(cors.Config{ AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}, AllowHeaders: []string{"Origin", "Content-Length", "Content-Type"}, AllowCredentials: true, AllowOriginFunc: func(origin string) bool { return true }, MaxAge: 12 * time.Hour, }))
router.Use(gin.ErrorLogger())
routes.GetRoutes(router)
config := utils.GetConfig() certDir := filepath.Join(config.ExecDir, "sslcerts") ok, _ := utils.PathExists(certDir) if ok && config.Https { router.RunTLS(fmt.Sprintf(":%d", config.Port), filepath.Join(certDir, "cert.pem"), filepath.Join(certDir, "key.pem")) } else { router.Run(fmt.Sprintf(":%d", config.Port)) } scheduler.StartAsync()}1234567891011121314151617181920212223242526272829303132333435363738394041package models
import ( "database/sql/driver" "encoding/json" "time")
type File struct { ID string `gorm:"type:text;primaryKey;default:generate_uid(16)"` Name string `gorm:"type:text;not null"` Type string `gorm:"type:text;not null"` MimeType string `gorm:"type:text;not null"` Path string `gorm:"type:text;index"` Size int64 `gorm:"type:bigint"` Starred *bool `gorm:"default:false"` Depth *int `gorm:"type:integer"` UserID int64 `gorm:"type:bigint;not null"` Status string `gorm:"type:text"` ParentID string `gorm:"type:text;index"` Parts *Parts `gorm:"type:jsonb"` ChannelID *int64 `gorm:"type:bigint"` CreatedAt time.Time `gorm:"default:timezone('utc'::text, now())"` UpdatedAt time.Time `gorm:"default:timezone('utc'::text, now())"`}
type Parts []Parttype Part struct { ID int64 `json:"id"`}
func (a Parts) Value() (driver.Value, error) { return json.Marshal(a)}
func (a *Parts) Scan(value interface{}) error { if err := json.Unmarshal(value.([]byte), &a); err != nil { return err } return nil}1234567891011121314151617package models
import ( "time")
type Upload struct { ID string `gorm:"type:text;primary_key;default:generate_uid(16)"` UploadId string `gorm:"type:text"` Name string `gorm:"type:text"` PartNo int `gorm:"type:integer"` TotalParts int `gorm:"type:integer"` PartId int `gorm:"type:integer"` ChannelID int64 `gorm:"type:bigint"` Size int64 `gorm:"type:bigint"` CreatedAt time.Time `gorm:"default:timezone('utc'::text, now())"`}123456789101112131415package models
import ( "time")
type User struct { UserId int64 `gorm:"type:bigint;primaryKey"` Name string `gorm:"type:text"` UserName string `gorm:"type:text"` IsPremium bool `gorm:"type:bool"` TgSession string `gorm:"type:text"` UpdatedAt time.Time `gorm:"default:timezone('utc'::text, now())"` CreatedAt time.Time `gorm:"default:timezone('utc'::text, now())"`}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950package routes
import ( "net/http"
"github.com/divyam234/teldrive/database" "github.com/divyam234/teldrive/services"
"github.com/gin-gonic/gin")
func addAuthRoutes(rg *gin.RouterGroup) {
r := rg.Group("/auth")
authService := services.AuthService{Db: database.DB, SessionMaxAge: 30 * 24 * 60 * 60, SessionCookieName: "user-session"}
r.POST("/login", func(c *gin.Context) {
res, err := authService.LogIn(c)
if err != nil { c.AbortWithError(err.Code, err.Error) return } c.JSON(http.StatusOK, res) })
r.GET("/logout", Authmiddleware, func(c *gin.Context) {
res, err := authService.Logout(c)
if err != nil { c.AbortWithError(err.Code, err.Error) return } c.JSON(http.StatusOK, res)
})
r.GET("/ws", authService.HandleMultipleLogin)
r.GET("/session", func(c *gin.Context) {
session := authService.GetSession(c)
c.JSON(http.StatusOK, session) })
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107package routes
import ( "net/http"
"github.com/divyam234/teldrive/database" "github.com/divyam234/teldrive/services" "github.com/divyam234/teldrive/utils"
"github.com/gin-gonic/gin")
func addFileRoutes(rg *gin.RouterGroup) {
r := rg.Group("/files") r.Use(Authmiddleware) fileService := services.FileService{Db: database.DB, ChannelID: utils.GetConfig().ChannelID}
r.GET("", func(c *gin.Context) { res, err := fileService.ListFiles(c)
if err != nil { c.AbortWithError(err.Code, err.Error) return }
c.JSON(http.StatusOK, res) })
r.POST("", func(c *gin.Context) {
res, err := fileService.CreateFile(c)
if err != nil { c.AbortWithError(err.Code, err.Error) return }
c.JSON(http.StatusOK, res) })
r.GET("/:fileID", func(c *gin.Context) {
res, err := fileService.GetFileByID(c)
if err != nil { c.AbortWithError(http.StatusNotFound, err) return }
c.JSON(http.StatusOK, res) })
r.PATCH("/:fileID", func(c *gin.Context) {
res, err := fileService.UpdateFile(c)
if err != nil { c.AbortWithError(err.Code, err.Error) return }
c.JSON(http.StatusOK, res) })
r.GET("/:fileID/:fileName", func(c *gin.Context) {
fileService.GetFileStream(c) })
r.POST("/movefiles", func(c *gin.Context) {
res, err := fileService.MoveFiles(c)
if err != nil { c.AbortWithError(err.Code, err.Error) return }
c.JSON(http.StatusOK, res) })
r.POST("/makekdir", func(c *gin.Context) {
res, err := fileService.MakeDirectory(c)
if err != nil { c.AbortWithError(err.Code, err.Error) return }
c.JSON(http.StatusOK, res) })
r.POST("/deletefiles", func(c *gin.Context) {
res, err := fileService.DeleteFiles(c)
if err != nil { c.AbortWithError(err.Code, err.Error) return }
c.JSON(http.StatusOK, res) })
}1234567891011package routes
import "github.com/gin-gonic/gin"
func GetRoutes(router *gin.Engine) { api := router.Group("/api") addAuthRoutes(api) addFileRoutes(api) addUploadRoutes(api) addUserRoutes(api)}12345678910111213141516171819202122232425262728293031323334353637383940414243444546package routes
import ( "net/http" "time"
"github.com/divyam234/teldrive/utils" "github.com/divyam234/teldrive/utils/auth" "github.com/gin-gonic/gin" "github.com/go-jose/go-jose/v3/jwt")
func Authmiddleware(c *gin.Context) {
if c.FullPath() == "/api/files/:fileID/:fileName" && utils.GetConfig().MultiClient { c.Next() } cookie, err := c.Request.Cookie("user-session")
if err != nil { c.JSON(http.StatusUnauthorized, gin.H{"error": "missing session cookie"}) c.Abort() return }
now := time.Now().UTC()
jwePayload, err := auth.Decode(cookie.Value)
if err != nil { c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()}) c.Abort() return }
if *jwePayload.Expiry < *jwt.NewNumericDate(now) { c.JSON(http.StatusUnauthorized, gin.H{"error": "token expired"}) c.Abort() return }
c.Set("jwtUser", jwePayload)
c.Next()
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455package routes
import ( "net/http"
"github.com/divyam234/teldrive/database" "github.com/divyam234/teldrive/services" "github.com/divyam234/teldrive/utils"
"github.com/gin-gonic/gin")
func addUploadRoutes(rg *gin.RouterGroup) {
r := rg.Group("/uploads") r.Use(Authmiddleware)
uploadService := services.UploadService{Db: database.DB, ChannelID: utils.GetConfig().ChannelID}
r.GET("/:id", func(c *gin.Context) {
res, err := uploadService.GetUploadFileById(c)
if err != nil { c.AbortWithError(http.StatusNotFound, err.Error) return }
c.JSON(http.StatusOK, res) })
r.POST("/:id", func(c *gin.Context) {
res, err := uploadService.UploadFile(c)
if err != nil { c.AbortWithError(err.Code, err.Error) return }
c.JSON(http.StatusOK, res) })
r.DELETE("/:id", func(c *gin.Context) { err := uploadService.DeleteUploadFile(c)
if err != nil { c.AbortWithError(err.Code, err.Error) return }
c.JSON(http.StatusOK, gin.H{"message": "upload deleted"}) })
}12345678910111213141516171819package routes
import ( "github.com/divyam234/teldrive/services"
"github.com/gin-gonic/gin")
func addUserRoutes(rg *gin.RouterGroup) { r := rg.Group("/users") r.Use(Authmiddleware) userService := services.UserService{}
r.GET("/profile", func(c *gin.Context) { if c.Query("photo") != "" { userService.GetProfilePhoto(c) } })}123456package schemas
type Message struct { Status bool `json:"status"` Message string `json:"message,omitempty"`}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778package schemas
import ( "time"
"github.com/divyam234/teldrive/models")
type PaginationQuery struct { PerPage int `form:"perPage"` NextPageToken string `form:"nextPageToken"`}
type SortingQuery struct { Sort string `form:"sort"` Order string `form:"order"`}
type FileQuery struct { Name string `form:"name" mapstructure:"name,omitempty"` Search string `form:"search" mapstructure:"search,omitempty"` Type string `form:"type" mapstructure:"type,omitempty"` Path string `form:"path" mapstructure:"path,omitempty"` Op string `form:"op" mapstructure:"op,omitempty"` Starred *bool `form:"starred" mapstructure:"starred,omitempty"` MimeType string `form:"mimeType" mapstructure:"mime_type,omitempty"` ParentID string `form:"parentId" mapstructure:"parent_id,omitempty"` UpdatedAt *time.Time `form:"updatedAt" mapstructure:"updated_at,omitempty"` Status string `mapstructure:"status"` UserID int64 `mapstructure:"user_id"`}
type FileIn struct { Name string `json:"name" mapstructure:"name,omitempty"` Type string `json:"type" mapstructure:"type,omitempty"` Parts *models.Parts `json:"parts,omitempty" mapstructure:"parts,omitempty"` MimeType string `json:"mimeType" mapstructure:"mime_type,omitempty"` ChannelID *int64 `json:"channelId,omitempty" mapstructure:"channel_id,omitempty"` Path string `json:"path" mapstructure:"path,omitempty"` Size int64 `json:"size" mapstructure:"size,omitempty"` Starred *bool `json:"starred" mapstructure:"starred,omitempty"` Depth *int `json:"depth,omitempty" mapstructure:"depth,omitempty"` Status string `mapstructure:"status,omitempty"` UserID int64 `json:"userId" mapstructure:"user_id,omitempty"` ParentID string `json:"parentId" mapstructure:"parent_id,omitempty"`}
type FileOut struct { ID string `json:"id"` Name string `json:"name"` Type string `json:"type"` MimeType string `json:"mimeType" mapstructure:"mime_type"` Path string `json:"path,omitempty" mapstructure:"path,omitempty"` Size int64 `json:"size,omitempty" mapstructure:"size,omitempty"` Starred *bool `json:"starred"` ParentID string `json:"parentId,omitempty" mapstructure:"parent_id"` UpdatedAt time.Time `json:"updatedAt,omitempty" mapstructure:"updated_at"`}
type FileResponse struct { Results []FileOut `json:"results"` NextPageToken string `json:"nextPageToken,omitempty"`}
type FileOutFull struct { FileOut Parts *models.Parts `json:"parts,omitempty"` ChannelID *int64 `json:"channelId"`}
type FileOperation struct { Files []string `json:"files"` Destination string `json:"destination,omitempty"`}
type MkDir struct { Path string `json:"path"`}123456789101112131415161718192021package schemas
type UploadQuery struct { Filename string `form:"fileName"` PartNo int `form:"partNo,omitempty"` TotalParts int `form:"totalparts"`}
type UploadPartOut struct { ID string `json:"id"` Name string `json:"name"` PartId int `json:"partId"` PartNo int `json:"partNo"` TotalParts int `json:"totalParts"` ChannelID int64 `json:"channelId"` Size int64 `json:"size"`}
type UploadOut struct { Parts []UploadPartOut `json:"parts"`}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347package services
import ( "bytes" "context" "encoding/base64" "encoding/binary" "encoding/json" "errors" "fmt" "log" "math/big" "net" "net/http" "strconv" "time"
"github.com/divyam234/teldrive/models" "github.com/divyam234/teldrive/schemas" "github.com/divyam234/teldrive/types" "github.com/divyam234/teldrive/utils" "github.com/divyam234/teldrive/utils/auth" "github.com/gin-gonic/gin" "github.com/go-jose/go-jose/v3/jwt" "github.com/gorilla/websocket" "github.com/gotd/td/session" tgauth "github.com/gotd/td/telegram/auth" "github.com/gotd/td/telegram/auth/qrlogin" "github.com/gotd/td/tg" "github.com/gotd/td/tgerr" "gorm.io/gorm")
type AuthService struct { Db *gorm.DB SessionMaxAge int SessionCookieName string}
type SessionData struct { Version int Data session.Data}type SocketMessage struct { AuthType string `json:"authType"` Message string `json:"message"` PhoneNo string `json:"phoneNo,omitempty"` PhoneCodeHash string `json:"phoneCodeHash,omitempty"` PhoneCode string `json:"phoneCode,omitempty"` Password string `json:"password,omitempty"`}
func IP4toInt(IPv4Address net.IP) int64 { IPv4Int := big.NewInt(0) IPv4Int.SetBytes(IPv4Address.To4()) return IPv4Int.Int64()}
func Pack32BinaryIP4(ip4Address string) []byte { ipv4Decimal := IP4toInt(net.ParseIP(ip4Address))
buf := new(bytes.Buffer) binary.Write(buf, binary.BigEndian, uint32(ipv4Decimal)) return buf.Bytes()}
func generateTgSession(dcID int, authKey []byte, port int) string {
dcMaps := map[int]string{ 1: "149.154.175.53", 2: "149.154.167.51", 3: "149.154.175.100", 4: "149.154.167.91", 5: "91.108.56.130", }
dcIDByte := byte(dcID) serverAddressBytes := Pack32BinaryIP4(dcMaps[dcID]) portByte := make([]byte, 2) binary.BigEndian.PutUint16(portByte, uint16(port))
packet := make([]byte, 0) packet = append(packet, dcIDByte) packet = append(packet, serverAddressBytes...) packet = append(packet, portByte...) packet = append(packet, authKey...)
base64Encoded := base64.URLEncoding.EncodeToString(packet) return "1" + base64Encoded}
func setCookie(c *gin.Context, key string, value string, age int) {
config := utils.GetConfig()
if config.CookieSameSite { c.SetSameSite(2) } else { c.SetSameSite(4) } c.SetCookie(key, value, age, "/", c.Request.Host, config.Https, true)
}
func (as *AuthService) LogIn(c *gin.Context) (*schemas.Message, *types.AppError) { var session types.TgSession if err := c.ShouldBindJSON(&session); err != nil { return nil, &types.AppError{Error: errors.New("invalid request payload"), Code: http.StatusBadRequest} }
now := time.Now().UTC()
jwtClaims := &types.JWTClaims{Claims: jwt.Claims{ Subject: strconv.FormatInt(session.UserID, 10), IssuedAt: jwt.NewNumericDate(now), Expiry: jwt.NewNumericDate(now.Add(time.Duration(as.SessionMaxAge) * time.Second)), }, TgSession: session.Sesssion, Name: session.Name, UserName: session.UserName, Bot: session.Bot, IsPremium: session.IsPremium, }
jweToken, err := auth.Encode(jwtClaims)
if err != nil { return nil, &types.AppError{Error: err, Code: http.StatusBadRequest} }
user := models.User{ UserId: session.UserID, Name: session.Name, UserName: session.UserName, IsPremium: session.IsPremium, TgSession: session.Sesssion, }
var result []models.User
if err := as.Db.Model(&models.User{}).Where("user_id = ?", session.UserID).Find(&result).Error; err != nil { return nil, &types.AppError{Error: errors.New("failed to create or update user"), Code: http.StatusInternalServerError} } if len(result) == 0 { if err := as.Db.Create(&user).Error; err != nil { return nil, &types.AppError{Error: errors.New("failed to create or update user"), Code: http.StatusInternalServerError} } //Create root folder on first login
file := &models.File{ Name: "root", Type: "folder", MimeType: "drive/folder", Path: "/", Depth: utils.IntPointer(0), UserID: session.UserID, Status: "active", ParentID: "root", } if err := as.Db.Create(file).Error; err != nil { return nil, &types.AppError{Error: errors.New("failed to create or update user"), Code: http.StatusInternalServerError} } } else { if err := as.Db.Model(&models.User{}).Where("user_id = ?", session.UserID).Update("tg_session", session.Sesssion).Error; err != nil { return nil, &types.AppError{Error: errors.New("failed to create or update user"), Code: http.StatusInternalServerError} } } setCookie(c, as.SessionCookieName, jweToken, as.SessionMaxAge) return &schemas.Message{Status: true, Message: "login success"}, nil}
func (as *AuthService) GetSession(c *gin.Context) *types.Session {
cookie, err := c.Request.Cookie(as.SessionCookieName)
if err != nil { return nil }
jwePayload, err := auth.Decode(cookie.Value)
if err != nil { return nil }
now := time.Now().UTC()
newExpires := now.Add(time.Duration(as.SessionMaxAge) * time.Second)
session := &types.Session{Name: jwePayload.Name, UserName: jwePayload.UserName, Expires: newExpires.Format(time.RFC3339)}
jwePayload.IssuedAt = jwt.NewNumericDate(now)
jwePayload.Expiry = jwt.NewNumericDate(newExpires)
jweToken, err := auth.Encode(jwePayload)
if err != nil { return nil } setCookie(c, as.SessionCookieName, jweToken, as.SessionMaxAge) return session}
func (as *AuthService) Logout(c *gin.Context) (*schemas.Message, *types.AppError) { val, _ := c.Get("jwtUser") jwtUser := val.(*types.JWTClaims) userId, _ := strconv.ParseInt(jwtUser.Subject, 10, 64)
client, _ := utils.GetAuthClient(c, jwtUser.TgSession, userId)
client.Run(c, func(ctx context.Context) error { _, err := client.API().AuthLogOut(c) return err })
setCookie(c, as.SessionCookieName, "", -1) return &schemas.Message{Status: true, Message: "logout success"}, nil}
func prepareSession(user *tg.User, data *session.Data) *types.TgSession { sessionString := generateTgSession(data.DC, data.AuthKey, 443) session := &types.TgSession{ Sesssion: sessionString, UserID: user.ID, Bot: user.Bot, UserName: user.Username, Name: fmt.Sprintf("%s %s", user.FirstName, user.LastName), IsPremium: user.Premium, } return session}
func (as *AuthService) HandleMultipleLogin(c *gin.Context) { upgrader := websocket.Upgrader{ CheckOrigin: func(r *http.Request) bool { return true }, } conn, err := upgrader.Upgrade(c.Writer, c.Request, nil) if err != nil { log.Println(err) return } defer conn.Close()
dispatcher := tg.NewUpdateDispatcher() loggedIn := qrlogin.OnLoginToken(dispatcher) sessionStorage := &session.StorageMemory{} tgClient, stop, _ := utils.StartNonAuthClient(dispatcher, sessionStorage)
defer stop()
for { message := &SocketMessage{} err := conn.ReadJSON(message)
if err != nil { log.Println(err) return } if message.AuthType == "qr" { go func() { authorization, err := tgClient.QR().Auth(c, loggedIn, func(ctx context.Context, token qrlogin.Token) error { conn.WriteJSON(map[string]interface{}{"type": "auth", "payload": map[string]string{"token": token.URL()}}) return nil })
if tgerr.Is(err, "SESSION_PASSWORD_NEEDED") { conn.WriteJSON(map[string]interface{}{"type": "auth", "message": "2FA required"}) return }
if err != nil { conn.WriteJSON(map[string]interface{}{"type": "error", "message": err.Error()}) return } user, ok := authorization.User.AsNotEmpty() if !ok { conn.WriteJSON(map[string]interface{}{"type": "error", "message": errors.New("auth failed")}) return } res, _ := sessionStorage.LoadSession(c) sessionData := &SessionData{} json.Unmarshal(res, sessionData) session := prepareSession(user, &sessionData.Data) conn.WriteJSON(map[string]interface{}{"type": "auth", "payload": session, "message": "success"}) }() } if message.AuthType == "phone" && message.Message == "sendcode" { go func() { res, err := tgClient.Auth().SendCode(c, message.PhoneNo, tgauth.SendCodeOptions{}) if err != nil { conn.WriteJSON(map[string]interface{}{"type": "error", "message": err.Error()}) return } code := res.(*tg.AuthSentCode) conn.WriteJSON(map[string]interface{}{"type": "auth", "payload": map[string]string{"phoneCodeHash": code.PhoneCodeHash}}) }() } if message.AuthType == "phone" && message.Message == "signin" { go func() { auth, err := tgClient.Auth().SignIn(c, message.PhoneNo, message.PhoneCode, message.PhoneCodeHash)
if errors.Is(err, tgauth.ErrPasswordAuthNeeded) { conn.WriteJSON(map[string]interface{}{"type": "auth", "message": "2FA required"}) return }
if err != nil { conn.WriteJSON(map[string]interface{}{"type": "error", "message": err.Error()}) return } user, ok := auth.User.AsNotEmpty() if !ok { conn.WriteJSON(map[string]interface{}{"type": "error", "message": errors.New("auth failed")}) return } res, _ := sessionStorage.LoadSession(c) sessionData := &SessionData{} json.Unmarshal(res, sessionData) session := prepareSession(user, &sessionData.Data) conn.WriteJSON(map[string]interface{}{"type": "auth", "payload": session, "message": "success"}) }() }
if message.AuthType == "2fa" && message.Password != "" { go func() { auth, err := tgClient.Auth().Password(c, message.Password) if err != nil { conn.WriteJSON(map[string]interface{}{"type": "error", "message": err.Error()}) return } user, ok := auth.User.AsNotEmpty() if !ok { conn.WriteJSON(map[string]interface{}{"type": "error", "message": errors.New("auth failed")}) return } res, _ := sessionStorage.LoadSession(c) sessionData := &SessionData{} json.Unmarshal(res, sessionData) session := prepareSession(user, &sessionData.Data) conn.WriteJSON(map[string]interface{}{"type": "auth", "payload": session, "message": "success"}) }() } }
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582package services
import ( "context" "encoding/base64" "errors" "fmt" "io" "math" "net/http" "strconv" "strings"
"github.com/divyam234/teldrive/cache" "github.com/divyam234/teldrive/models" "github.com/divyam234/teldrive/schemas" "github.com/divyam234/teldrive/utils"
"github.com/divyam234/teldrive/types"
"github.com/gin-gonic/gin" "github.com/gotd/td/telegram" "github.com/gotd/td/tg" "github.com/jackc/pgx/v5/pgconn" "github.com/mitchellh/mapstructure" range_parser "github.com/quantumsheep/range-parser" "gorm.io/gorm" "gorm.io/gorm/clause")
type FileService struct { Db *gorm.DB ChannelID int64}
func getAuthUserId(c *gin.Context) int64 { val, _ := c.Get("jwtUser") jwtUser := val.(*types.JWTClaims) userId, _ := strconv.ParseInt(jwtUser.Subject, 10, 64) return userId}
func (fs *FileService) CreateFile(c *gin.Context) (*schemas.FileOut, *types.AppError) { userId := getAuthUserId(c) var fileIn schemas.FileIn if err := c.ShouldBindJSON(&fileIn); err != nil { return nil, &types.AppError{Error: errors.New("invalid request payload"), Code: http.StatusBadRequest} }
fileIn.Path = strings.TrimSpace(fileIn.Path)
if fileIn.Path != "" { var parent models.File if err := fs.Db.Where("type = ? AND path = ?", "folder", fileIn.Path).First(&parent).Error; err != nil { return nil, &types.AppError{Error: errors.New("parent directory not found"), Code: http.StatusNotFound} } fileIn.ParentID = parent.ID }
if fileIn.Type == "folder" { fileIn.MimeType = "drive/folder" var fullPath string if fileIn.Path == "/" { fullPath = "/" + fileIn.Name } else { fullPath = fileIn.Path + "/" + fileIn.Name } fileIn.Path = fullPath fileIn.Depth = utils.IntPointer(len(strings.Split(fileIn.Path, "/")) - 1) } else if fileIn.Type == "file" { fileIn.Path = "" fileIn.ChannelID = &fs.ChannelID }
fileIn.UserID = userId fileIn.Starred = utils.BoolPointer(false) fileIn.Status = "active"
fileDb := mapFileInToFile(fileIn)
if err := fs.Db.Create(&fileDb).Error; err != nil { pgErr := err.(*pgconn.PgError) if pgErr.Code == "23505" { return nil, &types.AppError{Error: errors.New("file exists"), Code: http.StatusBadRequest} } return nil, &types.AppError{Error: errors.New("failed to create a file"), Code: http.StatusBadRequest}
}
res := mapFileToFileOut(fileDb)
return &res, nil}
func (fs *FileService) UpdateFile(c *gin.Context) (*schemas.FileOut, *types.AppError) {
fileID := c.Param("fileID")
var fileUpdate schemas.FileIn
var files []models.File
if err := c.ShouldBindJSON(&fileUpdate); err != nil { return nil, &types.AppError{Error: errors.New("invalid request payload"), Code: http.StatusBadRequest} }
if fileUpdate.Type == "folder" && fileUpdate.Name != "" { if err := fs.Db.Raw("select * from teldrive.update_folder(?, ?)", fileID, fileUpdate.Name).Scan(&files).Error; err != nil { return nil, &types.AppError{Error: errors.New("failed to update the file"), Code: http.StatusInternalServerError} } } else { fileDb := mapFileInToFile(fileUpdate) if err := fs.Db.Model(&files).Clauses(clause.Returning{}).Where("id = ?", fileID).Updates(fileDb).Error; err != nil { return nil, &types.AppError{Error: errors.New("failed to update the file"), Code: http.StatusInternalServerError} } }
if len(files) == 0 { return nil, &types.AppError{Error: errors.New("file not updated"), Code: http.StatusNotFound} }
file := mapFileToFileOut(files[0])
return &file, nil
}
func (fs *FileService) GetFileByID(c *gin.Context) (*schemas.FileOutFull, error) {
fileID := c.Param("fileID")
var file []models.File
fs.Db.Model(&models.File{}).Where("id = ?", fileID).Find(&file)
if len(file) == 0 { return nil, errors.New("file not found") }
return mapFileToFileOutFull(file[0]), nil}
func (fs *FileService) ListFiles(c *gin.Context) (*schemas.FileResponse, *types.AppError) {
userId := getAuthUserId(c)
var pagingParams schemas.PaginationQuery pagingParams.PerPage = 200 if err := c.ShouldBindQuery(&pagingParams); err != nil { return nil, &types.AppError{Error: errors.New(""), Code: http.StatusBadRequest} }
var sortingParams schemas.SortingQuery sortingParams.Order = "asc" sortingParams.Sort = "name" if err := c.ShouldBindQuery(&sortingParams); err != nil { return nil, &types.AppError{Error: errors.New(""), Code: http.StatusBadRequest} }
var fileQuery schemas.FileQuery fileQuery.Op = "list" fileQuery.Status = "active" fileQuery.UserID = userId if err := c.ShouldBindQuery(&fileQuery); err != nil { return nil, &types.AppError{Error: errors.New(""), Code: http.StatusBadRequest} }
query := fs.Db.Model(&models.File{}).Limit(pagingParams.PerPage). Where(map[string]interface{}{"user_id": userId, "status": "active"})
if fileQuery.Op == "list" {
if pathExists, message := fs.CheckIfPathExists(&fileQuery.Path); !pathExists { return nil, &types.AppError{Error: errors.New(message), Code: http.StatusNotFound} }
setOrderFilter(query, &pagingParams, &sortingParams)
query.Order("type DESC").Order(getOrder(sortingParams)). Where("parent_id in (?)", fs.Db.Model(&models.File{}).Select("id").Where("path = ?", fileQuery.Path))
} else if fileQuery.Op == "find" {
filterQuery := map[string]interface{}{}
err := mapstructure.Decode(fileQuery, &filterQuery)
if err != nil { return nil, &types.AppError{Error: err, Code: http.StatusBadRequest} }
delete(filterQuery, "op")
if filterQuery["updated_at"] == nil { delete(filterQuery, "updated_at") }
setOrderFilter(query, &pagingParams, &sortingParams)
query.Order("type DESC").Order(getOrder(sortingParams)).Where(filterQuery)
} else if fileQuery.Op == "search" {
query.Where("teldrive.get_tsquery(?) @@ teldrive.get_tsvector(name)", fileQuery.Search)
setOrderFilter(query, &pagingParams, &sortingParams) query.Order(getOrder(sortingParams))
}
var results []schemas.FileOut
query.Find(&results)
token := ""
if len(results) == pagingParams.PerPage { lastItem := results[len(results)-1] token = utils.GetField(&lastItem, utils.CamelToPascalCase(sortingParams.Sort)) token = base64.StdEncoding.EncodeToString([]byte(token)) }
res := &schemas.FileResponse{Results: results, NextPageToken: token}
return res, nil}
func (fs *FileService) CheckIfPathExists(path *string) (bool, string) { query := fs.Db.Model(&models.File{}).Select("id").Where("path = ?", path) var results []schemas.FileOut query.Find(&results) if len(results) == 0 { return false, "This directory doesn't exist." } return true, ""}
func (fs *FileService) MakeDirectory(c *gin.Context) (*schemas.FileOut, *types.AppError) {
var payload schemas.MkDir
var files []models.File
if err := c.ShouldBindJSON(&payload); err != nil { return nil, &types.AppError{Error: errors.New("invalid request payload"), Code: http.StatusBadRequest} }
userId := getAuthUserId(c) if err := fs.Db.Raw("select * from teldrive.create_directories(?, ?)", userId, payload.Path).Scan(&files).Error; err != nil { return nil, &types.AppError{Error: errors.New("failed to create directories"), Code: http.StatusInternalServerError} }
file := mapFileToFileOut(files[0])
return &file, nil
}
func (fs *FileService) MoveFiles(c *gin.Context) (*schemas.Message, *types.AppError) {
var payload schemas.FileOperation
if err := c.ShouldBindJSON(&payload); err != nil { return nil, &types.AppError{Error: errors.New("invalid request payload"), Code: http.StatusBadRequest} }
var destination models.File
if pathExists, message := fs.CheckIfPathExists(&payload.Destination); !pathExists { return nil, &types.AppError{Error: errors.New(message), Code: http.StatusBadRequest} }
if err := fs.Db.Model(&models.File{}).Select("id").Where("path = ?", payload.Destination).First(&destination).Error; errors.Is(err, gorm.ErrRecordNotFound) { return nil, &types.AppError{Error: errors.New("destination not found"), Code: http.StatusNotFound}
}
if err := fs.Db.Model(&models.File{}).Where("id IN ?", payload.Files).UpdateColumn("parent_id", destination.ID).Error; err != nil { return nil, &types.AppError{Error: errors.New("move failed"), Code: http.StatusInternalServerError} }
return &schemas.Message{Status: true, Message: "files moved"}, nil}
func (fs *FileService) DeleteFiles(c *gin.Context) (*schemas.Message, *types.AppError) {
var payload schemas.FileOperation
if err := c.ShouldBindJSON(&payload); err != nil { return nil, &types.AppError{Error: errors.New("invalid request payload"), Code: http.StatusBadRequest} }
if err := fs.Db.Exec("call teldrive.delete_files($1)", payload.Files).Error; err != nil { return nil, &types.AppError{Error: errors.New("failed to delete files"), Code: http.StatusInternalServerError} }
return &schemas.Message{Status: true, Message: "files deleted"}, nil}
func (fs *FileService) GetFileStream(c *gin.Context) {
w := c.Writer r := c.Request
fileID := c.Param("fileID")
var err error
res, err := cache.CachedFunction(fs.GetFileByID, fmt.Sprintf("files:%s", fileID))(c)
if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return }
file := res.(*schemas.FileOutFull)
w.Header().Set("Accept-Ranges", "bytes")
var start, end int64
rangeHeader := r.Header.Get("Range")
if rangeHeader == "" { start = 0 end = file.Size - 1 w.WriteHeader(http.StatusOK) } else { ranges, err := range_parser.Parse(file.Size, r.Header.Get("Range")) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } start = ranges[0].Start end = ranges[0].End w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, end, file.Size)) w.WriteHeader(http.StatusPartialContent) }
contentLength := end - start + 1
w.Header().Set("Content-Type", file.MimeType)
w.Header().Set("Content-Length", strconv.FormatInt(contentLength, 10))
disposition := "inline"
if c.Query("d") == "1" { disposition = "attachment" }
w.Header().Set("Content-Disposition", fmt.Sprintf("%s; filename=\"%s\"", disposition, file.Name))
client, idx := utils.GetDownloadClient(c)
defer func() { utils.GetClientWorkload().Dec(idx) }()
ir, iw := io.Pipe() parts, err := fs.getParts(c, client, file) if err != nil { return } parts = rangedParts(parts, int64(start), int64(end))
if r.Method != "HEAD" { go func() { defer iw.Close() for _, part := range parts { streamFilePart(c, client, iw, &part, part.Start, part.End, 1024*1024) } }() io.CopyN(w, ir, contentLength) }
}
func (fs *FileService) getParts(ctx context.Context, tgClient *telegram.Client, file *schemas.FileOutFull) ([]types.Part, error) {
ids := []tg.InputMessageID{}
for _, part := range *file.Parts { ids = append(ids, tg.InputMessageID{ID: int(part.ID)}) }
s := make([]tg.InputMessageClass, len(ids))
for i := range ids { s[i] = &ids[i] }
api := tgClient.API()
res, err := cache.CachedFunction(utils.GetChannelById, fmt.Sprintf("channels:%d", fs.ChannelID))(ctx, api, fs.ChannelID)
if err != nil { return nil, err }
channel := res.(*tg.Channel)
messageRequest := tg.ChannelsGetMessagesRequest{Channel: &tg.InputChannel{ChannelID: fs.ChannelID, AccessHash: channel.AccessHash}, ID: s}
res, err = cache.CachedFunction(api.ChannelsGetMessages, fmt.Sprintf("messages:%s", file.ID))(ctx, &messageRequest)
if err != nil { return nil, err }
messages := res.(*tg.MessagesChannelMessages)
parts := []types.Part{}
for _, message := range messages.Messages { item := message.(*tg.Message) media := item.Media.(*tg.MessageMediaDocument) document := media.Document.(*tg.Document) location := document.AsInputDocumentFileLocation() parts = append(parts, types.Part{Location: location, Start: 0, End: document.Size - 1, Size: document.Size}) } return parts, nil}
func mapFileToFileOut(file models.File) schemas.FileOut { return schemas.FileOut{ ID: file.ID, Name: file.Name, Type: file.Type, MimeType: file.MimeType, Path: file.Path, Size: file.Size, Starred: file.Starred, ParentID: file.ParentID, UpdatedAt: file.UpdatedAt, }}
func mapFileInToFile(file schemas.FileIn) models.File { return models.File{ Name: file.Name, Type: file.Type, MimeType: file.MimeType, Path: file.Path, Size: file.Size, Starred: file.Starred, Depth: file.Depth, UserID: file.UserID, ParentID: file.ParentID, Parts: file.Parts, ChannelID: file.ChannelID, Status: file.Status, }}
func mapFileToFileOutFull(file models.File) *schemas.FileOutFull { return &schemas.FileOutFull{ FileOut: mapFileToFileOut(file), Parts: file.Parts, ChannelID: file.ChannelID, }}
func setOrderFilter(query *gorm.DB, pagingParams *schemas.PaginationQuery, sortingParams *schemas.SortingQuery) *gorm.DB { if pagingParams.NextPageToken != "" { sortColumn := sortingParams.Sort if sortColumn == "name" { sortColumn = "name collate numeric" } else { sortColumn = utils.CamelToSnake(sortingParams.Sort) }
tokenValue, err := base64.StdEncoding.DecodeString(pagingParams.NextPageToken) if err == nil { if sortingParams.Order == "asc" { return query.Where(fmt.Sprintf("%s > ?", sortColumn), string(tokenValue)) } else { return query.Where(fmt.Sprintf("%s < ?", sortColumn), string(tokenValue)) } } } return query}
func getOrder(sortingParams schemas.SortingQuery) string { sortColumn := utils.CamelToSnake(sortingParams.Sort) if sortingParams.Sort == "name" { sortColumn = "name collate numeric" }
return fmt.Sprintf("%s %s", sortColumn, strings.ToUpper(sortingParams.Order))}
func chunk(ctx context.Context, tgClient *telegram.Client, part *types.Part, offset int64, limit int64) ([]byte, error) {
req := &tg.UploadGetFileRequest{ Offset: offset, Limit: int(limit), Location: part.Location, }
r, err := tgClient.API().UploadGetFile(ctx, req)
if err != nil { return nil, err }
switch result := r.(type) { case *tg.UploadFile: return result.Bytes, nil default: return nil, fmt.Errorf("unexpected type %T", r) }}
func totalParts(start, end, chunkSize int64) int {
totalBytes := end - start + 1 parts := totalBytes / chunkSize
if totalBytes%chunkSize != 0 { parts++ }
return int(parts)}
func streamFilePart(ctx context.Context, tgClient *telegram.Client, writer *io.PipeWriter, part *types.Part, start, end, chunkSize int64) error {
offset := start - (start % chunkSize) firstPartCut := start - offset lastPartCut := (end % chunkSize) + 1
partCount := totalParts(start, end, chunkSize)
currentPart := 1
for { r, _ := chunk(ctx, tgClient, part, offset, chunkSize)
if len(r) == 0 { break } else if partCount == 1 { r = r[firstPartCut:lastPartCut]
} else if currentPart == 1 { r = r[firstPartCut:]
} else if currentPart == partCount { r = r[:lastPartCut]
}
writer.Write(r)
currentPart++
offset += chunkSize
if currentPart > partCount { break }
}
return nil}
func rangedParts(parts []types.Part, start, end int64) []types.Part {
chunkSize := parts[0].Size
startPartNumber := utils.Max(int64(math.Ceil(float64(start)/float64(chunkSize)))-1, 0)
endPartNumber := int64(math.Ceil(float64(end) / float64(chunkSize)))
partsToDownload := parts[startPartNumber:endPartNumber] partsToDownload[0].Start = start % chunkSize partsToDownload[len(partsToDownload)-1].End = end % chunkSize
return partsToDownload}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167package services
import ( "context" "errors" "fmt" "net/http"
"github.com/divyam234/teldrive/cache" "github.com/divyam234/teldrive/schemas" "github.com/divyam234/teldrive/utils"
"github.com/divyam234/teldrive/types"
"github.com/divyam234/teldrive/models" "github.com/gin-gonic/gin" "github.com/gotd/td/telegram/message" "github.com/gotd/td/telegram/uploader" "github.com/gotd/td/tg" "gorm.io/gorm")
type UploadService struct { Db *gorm.DB ChannelID int64}
func (us *UploadService) GetUploadFileById(c *gin.Context) (*schemas.UploadOut, *types.AppError) { uploadId := c.Param("id") parts := []schemas.UploadPartOut{} if err := us.Db.Model(&models.Upload{}).Order("part_no").Where("upload_id = ?", uploadId).Find(&parts).Error; err != nil { return nil, &types.AppError{Error: errors.New("failed to fetch from db"), Code: http.StatusInternalServerError} }
return &schemas.UploadOut{Parts: parts}, nil}
func (us *UploadService) DeleteUploadFile(c *gin.Context) *types.AppError { uploadId := c.Param("id") if err := us.Db.Where("upload_id = ?", uploadId).Delete(&models.Upload{}).Error; err != nil { return &types.AppError{Error: errors.New("failed to delete upload"), Code: http.StatusInternalServerError} }
return nil}
func (us *UploadService) UploadFile(c *gin.Context) (*schemas.UploadPartOut, *types.AppError) {
var uploadQuery schemas.UploadQuery
uploadQuery.PartNo = 1 uploadQuery.TotalParts = 1
if err := c.ShouldBindQuery(&uploadQuery); err != nil { return nil, &types.AppError{Error: err, Code: http.StatusBadRequest} }
if uploadQuery.Filename == "" { return nil, &types.AppError{Error: errors.New("filename missing"), Code: http.StatusBadRequest} }
uploadId := c.Param("id")
var uploadPart []models.Upload
us.Db.Model(&models.Upload{}).Where("upload_id = ?", uploadId).Where("part_no = ?", uploadQuery.PartNo).Find(&uploadPart)
if len(uploadPart) == 1 { out := mapSchema(&uploadPart[0]) return out, nil }
client, idx := utils.GetUploadClient(c)
file := c.Request.Body
fileSize := c.Request.ContentLength
fileName := uploadQuery.Filename
var msgId int
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer func() { if idx != -1 { utils.GetClientWorkload().Dec(idx) } cancel() }()
err := client.Run(ctx, func(ctx context.Context) error {
api := client.API()
u := uploader.NewUploader(api).WithThreads(8).WithPartSize(512 * 1024)
upload, err := u.Upload(c, uploader.NewUpload(fileName, file, fileSize))
if err != nil { return err }
document := message.UploadedDocument(upload).Filename(fileName).ForceFile(true)
res, err := cache.CachedFunction(utils.GetChannelById, fmt.Sprintf("channels:%d", us.ChannelID))(c, client.API(), us.ChannelID)
if err != nil { return err }
channel := res.(*tg.Channel)
sender := message.NewSender(client.API())
target := sender.To(&tg.InputPeerChannel{ChannelID: channel.ID, AccessHash: channel.AccessHash})
res, err = target.Media(c, document)
if err != nil { return err }
updates := res.(*tg.Updates)
msgId = updates.Updates[0].(*tg.UpdateMessageID).ID
return nil })
if err != nil { return nil, &types.AppError{Error: err, Code: http.StatusInternalServerError} }
partUpload := &models.Upload{ Name: fileName, UploadId: uploadId, PartId: msgId, ChannelID: us.ChannelID, Size: fileSize, PartNo: uploadQuery.PartNo, TotalParts: uploadQuery.TotalParts, }
if err := us.Db.Create(partUpload).Error; err != nil { return nil, &types.AppError{Error: errors.New("failed to upload part"), Code: http.StatusInternalServerError} }
out := mapSchema(partUpload)
return out, nil}
func mapSchema(in *models.Upload) *schemas.UploadPartOut { out := &schemas.UploadPartOut{ ID: in.ID, Name: in.Name, PartId: in.PartId, ChannelID: in.ChannelID, PartNo: in.PartNo, TotalParts: in.TotalParts, Size: in.Size, } return out}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091package services
import ( "bytes" "context" "fmt" "net/http" "strconv"
"github.com/divyam234/teldrive/types" "github.com/divyam234/teldrive/utils" "github.com/gotd/td/telegram" "github.com/gotd/td/tg"
"github.com/gin-gonic/gin")
type UserService struct {}
func getChunk(ctx context.Context, tgClient *telegram.Client, location tg.InputFileLocationClass, offset int64, limit int) ([]byte, error) {
req := &tg.UploadGetFileRequest{ Offset: offset, Limit: int(limit), Location: location, }
r, err := tgClient.API().UploadGetFile(ctx, req)
if err != nil { return nil, err }
switch result := r.(type) { case *tg.UploadFile: return result.Bytes, nil default: return nil, fmt.Errorf("unexpected type %T", r) }}
func iterContent(ctx context.Context, tgClient *telegram.Client, location tg.InputFileLocationClass) (*bytes.Buffer, error) { offset := int64(0) limit := 1024 * 1024 buff := &bytes.Buffer{} for { r, err := getChunk(ctx, tgClient, location, offset, limit) if err != nil { return buff, err } if len(r) == 0 { break } buff.Write(r) offset += int64(limit) } return buff, nil}
func (us *UserService) GetProfilePhoto(c *gin.Context) { val, _ := c.Get("jwtUser") jwtUser := val.(*types.JWTClaims) userId, _ := strconv.ParseInt(jwtUser.Subject, 10, 64) client, _ := utils.GetAuthClient(c, jwtUser.TgSession, userId)
err := client.Run(c, func(ctx context.Context) error { self, err := client.Self(c) if err != nil { return err } peer := self.AsInputPeer() photo, _ := self.Photo.AsNotEmpty() location := &tg.InputPeerPhotoFileLocation{Big: false, Peer: peer, PhotoID: photo.PhotoID} buff, err := iterContent(c, client, location) if err != nil { return err } content := buff.Bytes() c.Writer.Header().Set("Content-Type", "image/jpeg") c.Writer.Header().Set("Cache-Control", "public, max-age=86400") c.Writer.Header().Set("Content-Length", strconv.Itoa(len(content))) c.Writer.Header().Set("Content-Disposition", fmt.Sprintf("inline; filename=\"%s\"", "profile.jpeg")) c.Writer.Write(content) return nil }) if err != nil { http.Error(c.Writer, err.Error(), http.StatusBadRequest) return }}12345678910111213141516171819202122232425262728293031323334353637383940414243package types
import ( "github.com/go-jose/go-jose/v3/jwt" "github.com/gotd/td/tg")
type AppError struct { Error error Code int}
type Part struct { Location *tg.InputDocumentFileLocation Size int64 Start int64 End int64}
type JWTClaims struct { jwt.Claims TgSession string `json:"tgSession"` Name string `json:"name"` UserName string `json:"userName"` Bot bool `json:"bot"` IsPremium bool `json:"isPremium"`}
type TgSession struct { Sesssion string `json:"session"` UserID int64 `json:"userId"` Bot bool `json:"bot"` UserName string `json:"userName"` Name string `json:"name"` IsPremium bool `json:"isPremium"`}
type Session struct { Name string `json:"name"` UserName string `json:"userName"` IsPremium bool `json:"isPremium"` Expires string `json:"expires"`}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162package auth
import ( "encoding/json" "os"
"github.com/divyam234/teldrive/types" "github.com/go-jose/go-jose/v3")
func Encode(payload *types.JWTClaims) (string, error) {
rcpt := jose.Recipient{ Algorithm: jose.PBES2_HS256_A128KW, Key: os.Getenv("JWT_SECRET"), }
enc, err := jose.NewEncrypter(jose.A128CBC_HS256, rcpt, nil)
if err != nil { return "", err }
jwt, _ := json.Marshal(payload)
jweObject, err := enc.Encrypt(jwt)
if err != nil { return "", err }
jweToken, err := jweObject.CompactSerialize()
if err != nil { return "", err } return jweToken, nil}
func Decode(token string) (*types.JWTClaims, error) { jwe, err := jose.ParseEncrypted(token) if err != nil { return nil, err }
decryptedData, err := jwe.Decrypt(os.Getenv("JWT_SECRET"))
if err != nil { return nil, err }
jwtToken := &types.JWTClaims{}
err = json.Unmarshal(decryptedData, jwtToken)
if err != nil { return nil, err }
return jwtToken, nil
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051package utils
import ( "path/filepath"
"github.com/joho/godotenv" "github.com/kelseyhightower/envconfig")
type MultiToken string
type Config struct { AppId int `envconfig:"APP_ID" required:"true"` AppHash string `envconfig:"APP_HASH" required:"true"` ChannelID int64 `envconfig:"CHANNEL_ID" required:"true"` JwtSecret string `envconfig:"JWT_SECRET" required:"true"` MultiClient bool `envconfig:"MULTI_CLIENT" default:"false"` Https bool `envconfig:"HTTPS" default:"false"` CookieSameSite bool `envconfig:"COOKIE_SAME_SITE" default:"true"` DatabaseUrl string `envconfig:"DATABASE_URL" required:"true"` RateLimit bool `envconfig:"RATE_LIMIT" default:"true"` TgClientDeviceModel string `envconfig:"TG_CLIENT_DEVICE_MODEL" required:"true"` TgClientSystemVersion string `envconfig:"TG_CLIENT_SYSTEM_VERSION" default:"Win32"` TgClientAppVersion string `envconfig:"TG_CLIENT_APP_VERSION" default:"2.1.9 K"` TgClientLangCode string `envconfig:"TG_CLIENT_LANG_CODE" default:"en"` TgClientSystemLangCode string `envconfig:"TG_CLIENT_SYSTEM_LANG_CODE" default:"en"` TgClientLangPack string `envconfig:"TG_CLIENT_LANG_PACK" default:"webk"` RunMigrations bool `envconfig:"RUN_MIGRATIONS" default:"true"` Port int `envconfig:"PORT" default:"8080"` ExecDir string}
var config Config
func InitConfig() {
execDir := getExecutableDir()
godotenv.Load(filepath.Join(execDir, ".env"))
godotenv.Load(filepath.Join(execDir, "teldrive.env")) err := envconfig.Process("", &config) if err != nil { panic(err) } config.ExecDir = execDir}
func GetConfig() *Config { return &config}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172package cron
import ( "context" "fmt"
"github.com/divyam234/teldrive/cache" "github.com/divyam234/teldrive/database" "github.com/divyam234/teldrive/models" "github.com/divyam234/teldrive/utils" "github.com/gotd/td/tg")
type Result struct { ID string Parts models.Parts TgSession string UserId int64 ChannelId int64}
func deleteTGMessage(ctx context.Context, client *tg.Client, result Result) error {
ids := make([]int, len(result.Parts))
for i, part := range result.Parts { ids[i] = int(part.ID) }
res, err := cache.CachedFunction(utils.GetChannelById, fmt.Sprintf("channels:%d", result.ChannelId))(ctx, client, result.ChannelId)
if err != nil { return err }
channel := res.(*tg.Channel)
messageDeleteRequest := tg.ChannelsDeleteMessagesRequest{Channel: &tg.InputChannel{ChannelID: result.ChannelId, AccessHash: channel.AccessHash}, ID: ids}
_, err = client.ChannelsDeleteMessages(ctx, &messageDeleteRequest) if err != nil { return err } return nil}
func FilesDeleteJob() { db := database.DB ctx := context.Background() var results []Result if err := db.Model(&models.File{}).Select("files.id", "files.parts", "files.user_id", "files.channel_id", "u.tg_session"). Joins("left join teldrive.users as u on u.user_id = files.user_id"). Where("status = ?", "pending_deletion").Scan(&results).Error; err != nil { return }
for _, file := range results { client, err := utils.GetAuthClient(ctx, file.TgSession, file.UserId) if err != nil { break } err = client.Run(ctx, func(ctx context.Context) error { err = deleteTGMessage(ctx, client.API(), file) return err })
if err == nil { db.Where("id = ?", file.ID).Delete(&models.File{}) } }}12345678910111213141516171819package utils
import ( "os"
"go.uber.org/zap" "go.uber.org/zap/zapcore")
var Logger *zap.Logger
func InitializeLogger() { config := zap.NewProductionEncoderConfig() config.EncodeTime = zapcore.ISO8601TimeEncoder consoleEncoder := zapcore.NewConsoleEncoder(config) defaultLogLevel := zapcore.DebugLevel core := zapcore.NewCore(consoleEncoder, zapcore.AddSync(os.Stdout), defaultLogLevel) Logger = zap.New(core, zap.AddCaller(), zap.AddStacktrace(zapcore.ErrorLevel))}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113package utils
import ( "context" "fmt" "os" "path/filepath" "regexp" "strings" "time"
"reflect"
"github.com/gotd/td/tg" "golang.org/x/exp/constraints"
"unicode")
func Max[T constraints.Ordered](a, b T) T { if a > b { return a } return b}
func CamelToPascalCase(input string) string { var result strings.Builder upperNext := true
for _, char := range input { if unicode.IsLetter(char) || unicode.IsDigit(char) { if upperNext { result.WriteRune(unicode.ToUpper(char)) upperNext = false } else { result.WriteRune(char) } } else { upperNext = true } }
return result.String()}
func CamelToSnake(input string) string { re := regexp.MustCompile("([a-z0-9])([A-Z])") snake := re.ReplaceAllString(input, "${1}_${2}") return strings.ToLower(snake)}
func GetField(v interface{}, field string) string { r := reflect.ValueOf(v) f := reflect.Indirect(r).FieldByName(field) fieldValue := f.Interface()
switch v := fieldValue.(type) { case string: return v case time.Time: return v.Format(time.RFC3339) default: return "" }}
func GetChannelById(ctx context.Context, client *tg.Client, channelID int64) (*tg.Channel, error) { inputChannel := &tg.InputChannel{ ChannelID: channelID, AccessHash: 0, } channels, err := client.ChannelsGetChannels(ctx, []tg.InputChannelClass{inputChannel})
if err != nil { return nil, fmt.Errorf("failed to fetch channel: %w", err) }
if len(channels.GetChats()) == 0 { return nil, fmt.Errorf("no channels found") }
channel := channels.GetChats()[0].(*tg.Channel) return channel, nil}
func BoolPointer(b bool) *bool { return &b}
func IntPointer(b int) *int { return &b}
func PathExists(path string) (bool, error) { _, err := os.Stat(path) if err == nil { return true, nil } if os.IsNotExist(err) { return false, nil } return false, err}
func getExecutableDir() string {
path, _ := os.Executable()
executableDir := filepath.Dir(path)
return executableDir}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297package utils
import ( "context" "fmt" "os" "path/filepath" "sort" "strconv" "strings" "sync" "time"
"github.com/cenkalti/backoff/v4" "github.com/divyam234/teldrive/types" "github.com/gin-gonic/gin" "github.com/gotd/contrib/bg" "github.com/gotd/contrib/middleware/floodwait" "github.com/gotd/contrib/middleware/ratelimit" tdclock "github.com/gotd/td/clock" "github.com/gotd/td/session" "github.com/gotd/td/telegram" "github.com/pkg/errors" "go.uber.org/zap" "golang.org/x/time/rate")
var clients map[int64]*telegram.Client
type Workload struct { mu sync.Mutex workloads map[int]int}
func (w *Workload) Set(key int, value int) { w.mu.Lock() defer w.mu.Unlock() w.workloads[key] = value}
func (w *Workload) Get(key int) int { w.mu.Lock() defer w.mu.Unlock() return w.workloads[key]}
func (w *Workload) Inc(key int) { w.mu.Lock() defer w.mu.Unlock() w.workloads[key]++}
func (w *Workload) Dec(key int) { w.mu.Lock() defer w.mu.Unlock() w.workloads[key]--}
func (w *Workload) GetMinIndex() int { w.mu.Lock() defer w.mu.Unlock() smallest := w.workloads[0] idx := 0 for i, workload := range clientWorkload.workloads { if workload < smallest { smallest = workload idx = i } } return idx}
var clientWorkload *Workload
func GetClientWorkload() *Workload { return clientWorkload}
func getDeviceConfig() telegram.DeviceConfig { appConfig := GetConfig() config := telegram.DeviceConfig{ DeviceModel: appConfig.TgClientDeviceModel, SystemVersion: appConfig.TgClientSystemVersion, AppVersion: appConfig.TgClientAppVersion, SystemLangCode: appConfig.TgClientSystemLangCode, LangPack: appConfig.TgClientLangPack, LangCode: appConfig.TgClientLangCode, } return config}
func reconnectionBackoff() backoff.BackOff { _clock := tdclock.System b := backoff.NewExponentialBackOff() b.Multiplier = 1.1 b.MaxElapsedTime = time.Duration(120) * time.Second b.Clock = _clock return b}
func GetBotClient(clientName string) *telegram.Client {
config := GetConfig() sessionStorage := &telegram.FileSessionStorage{ Path: filepath.Join(config.ExecDir, "sessions", clientName+".json"), }
middlewares := []telegram.Middleware{floodwait.NewSimpleWaiter()}
if config.RateLimit { middlewares = append(middlewares, ratelimit.New(rate.Every(time.Millisecond*100), 5)) }
options := telegram.Options{ SessionStorage: sessionStorage, Middlewares: middlewares, ReconnectionBackoff: reconnectionBackoff, RetryInterval: 5 * time.Second, MaxRetries: 5, Device: getDeviceConfig(), Clock: tdclock.System, }
client := telegram.NewClient(config.AppId, config.AppHash, options)
return client
}
func GetAuthClient(ctx context.Context, sessionStr string, userId int64) (*telegram.Client, error) {
data, err := session.TelethonSession(sessionStr)
if err != nil { return nil, err }
var ( storage = new(session.StorageMemory) loader = session.Loader{Storage: storage} )
if err := loader.Save(ctx, data); err != nil { return nil, err }
middlewares := []telegram.Middleware{floodwait.NewSimpleWaiter()}
if config.RateLimit { middlewares = append(middlewares, ratelimit.New(rate.Every(time.Millisecond*100), 5)) }
client := telegram.NewClient(config.AppId, config.AppHash, telegram.Options{ SessionStorage: storage, Middlewares: middlewares, ReconnectionBackoff: reconnectionBackoff, RetryInterval: 5 * time.Second, MaxRetries: 5, Device: getDeviceConfig(), Clock: tdclock.System, })
return client, nil}
func StartNonAuthClient(handler telegram.UpdateHandler, storage telegram.SessionStorage) (*telegram.Client, bg.StopFunc, error) { middlewares := []telegram.Middleware{} if config.RateLimit { middlewares = append(middlewares, ratelimit.New(rate.Every(time.Millisecond*100), 5)) } client := telegram.NewClient(config.AppId, config.AppHash, telegram.Options{ SessionStorage: storage, Middlewares: middlewares, Device: getDeviceConfig(), UpdateHandler: handler, })
stop, err := bg.Connect(client)
if err != nil { return nil, nil, err }
return client, stop, nil}
func startBotClient(ctx context.Context, client *telegram.Client, token string) (bg.StopFunc, error) {
stop, err := bg.Connect(client)
if err != nil { return nil, errors.Wrap(err, "failed to start client") }
tguser, err := client.Self(ctx)
if err != nil {
if _, err := client.Auth().Bot(ctx, token); err != nil { return nil, err } tguser, _ = client.Self(ctx) }
Logger.Info("started Client", zap.String("user", tguser.Username)) return stop, nil}
func startAuthClient(c *gin.Context, client *telegram.Client) (bg.StopFunc, error) { stop, err := bg.Connect(client)
if err != nil { return nil, err }
tguser, err := client.Self(c)
if err != nil { return nil, err }
Logger.Info("started Client", zap.String("user", tguser.Username))
clients[tguser.GetID()] = client
return stop, nil}
func InitBotClients() {
ctx := context.Background()
clients = make(map[int64]*telegram.Client)
clientWorkload = &Workload{workloads: make(map[int]int)}
if config.MultiClient {
if err := os.MkdirAll(filepath.Join(config.ExecDir, "sessions"), 0700); err != nil { return }
var keysToSort []string
for _, e := range os.Environ() { if strings.HasPrefix(e, "MULTI_TOKEN") { if i := strings.Index(e, "="); i >= 0 { keysToSort = append(keysToSort, e[:i]) } } }
sort.Strings(keysToSort)
for idx, key := range keysToSort { client := GetBotClient(fmt.Sprintf("client%d", idx)) clientWorkload.Set(idx, 0) clients[int64(idx)] = client go func(k string) { startBotClient(ctx, client, os.Getenv(k)) }(key) }
}}
func GetUploadClient(c *gin.Context) (*telegram.Client, int) { if config.MultiClient { idx := clientWorkload.GetMinIndex() clientWorkload.Inc(idx) return GetBotClient(fmt.Sprintf("client%d", idx)), idx } else { val, _ := c.Get("jwtUser") jwtUser := val.(*types.JWTClaims) userId, _ := strconv.ParseInt(jwtUser.Subject, 10, 64) client, _ := GetAuthClient(c, jwtUser.TgSession, userId) return client, -1 }}
func GetDownloadClient(c *gin.Context) (*telegram.Client, int) { if config.MultiClient { idx := clientWorkload.GetMinIndex() clientWorkload.Inc(idx) return clients[int64(idx)], idx } else { val, _ := c.Get("jwtUser") jwtUser := val.(*types.JWTClaims) userId, _ := strconv.ParseInt(jwtUser.Subject, 10, 64) if client, ok := clients[userId]; ok { return client, -1 } client, _ := GetAuthClient(c, jwtUser.TgSession, userId) startAuthClient(c, client) return client, -1 }}app/.github/buildkit.tomlAdded+2
app/.github/dependabot.ymlAdded+13
app/.github/workflows/build.ymlAdded+43
app/.github/workflows/goreleaser.ymlAdded+30
app/.gitignoreAdded+30
app/.goreleaser.yamlAdded+32
app/.vscode/launch.jsonAdded+15
app/DockerfileAdded+37
app/LICENSEAdded+674
app/README.mdAdded+159
app/cache/bigcache.goAdded+99
app/cache/cache.goAdded+72
app/cache/cachutil.goAdded+63
app/database/database.goAdded+77
app/database/migrations/20230817172319_init.sqlAdded+66
app/database/migrations/20230817172325_tables.sqlAdded+88
app/database/migrations/20230817172329_functions.sqlAdded+188
app/database/migrations/20230820014560_create_dirs_from_path.sqlAdded+48
app/docker-compose.ymlAdded+33
app/go.modAdded+74
app/go.sumAdded+261
app/haproxy.cfgAdded+24
app/main.goAdded+64
app/models/file.model.goAdded+41
app/models/upload.model.goAdded+17
app/models/user.model.goAdded+15
app/public/demo.pngAdded

app/routes/auth.goAdded+50
app/routes/file.goAdded+107
app/routes/main.goAdded+11
app/routes/middleware.goAdded+46
app/routes/upload.goAdded+55
app/routes/user.goAdded+19
app/schemas/common.goAdded+6
app/schemas/file.schema.goAdded+78
app/schemas/upload.schema.goAdded+21
app/services/auth.service.goAdded+347
app/services/file.service.goAdded+582
app/services/upload.service.goAdded+167
app/services/user.service.goAdded+91
app/types/main.goAdded+43
app/utils/auth/jwe.goAdded+62
app/utils/config.goAdded+51
app/utils/cron/cron.goAdded+72
app/utils/logger.goAdded+19
app/utils/main.goAdded+113
app/utils/tgclient.goAdded+297