Compare commits
30
Commits
3f941de9c8
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
af9d6d6eb9 | ||
|
|
43e119f12c | ||
|
|
16e3583927 | ||
|
|
51c4837aaf | ||
|
|
548075696c | ||
|
|
c798bdad5c | ||
|
|
90c85e9310 | ||
|
|
84e4c70b47 | ||
|
|
33dffdad95 | ||
|
|
1910e74085 | ||
|
|
21caa0f7e4 | ||
|
|
561b4feee1 | ||
|
|
3d57e589e6 | ||
|
|
e75784599e | ||
|
|
fb93746ba6 | ||
|
|
acbfdbe8eb | ||
|
|
ff1033dfb4 | ||
|
|
ab06bed6ec | ||
|
|
6190379c74 | ||
|
|
5225628f8a | ||
|
|
7f446fc953 | ||
|
|
eb32775986 | ||
|
|
6d479bb925 | ||
|
|
df18b29087 | ||
|
|
450923be2f | ||
|
|
b62a7a7a28 | ||
|
|
1196033364 | ||
|
|
55d2ac2b97 | ||
|
|
6647e54b8d | ||
|
|
c9508770a9 |
@@ -0,0 +1,373 @@
|
|||||||
|
Mozilla Public License Version 2.0
|
||||||
|
==================================
|
||||||
|
|
||||||
|
1. Definitions
|
||||||
|
--------------
|
||||||
|
|
||||||
|
1.1. "Contributor"
|
||||||
|
means each individual or legal entity that creates, contributes to
|
||||||
|
the creation of, or owns Covered Software.
|
||||||
|
|
||||||
|
1.2. "Contributor Version"
|
||||||
|
means the combination of the Contributions of others (if any) used
|
||||||
|
by a Contributor and that particular Contributor's Contribution.
|
||||||
|
|
||||||
|
1.3. "Contribution"
|
||||||
|
means Covered Software of a particular Contributor.
|
||||||
|
|
||||||
|
1.4. "Covered Software"
|
||||||
|
means Source Code Form to which the initial Contributor has attached
|
||||||
|
the notice in Exhibit A, the Executable Form of such Source Code
|
||||||
|
Form, and Modifications of such Source Code Form, in each case
|
||||||
|
including portions thereof.
|
||||||
|
|
||||||
|
1.5. "Incompatible With Secondary Licenses"
|
||||||
|
means
|
||||||
|
|
||||||
|
(a) that the initial Contributor has attached the notice described
|
||||||
|
in Exhibit B to the Covered Software; or
|
||||||
|
|
||||||
|
(b) that the Covered Software was made available under the terms of
|
||||||
|
version 1.1 or earlier of the License, but not also under the
|
||||||
|
terms of a Secondary License.
|
||||||
|
|
||||||
|
1.6. "Executable Form"
|
||||||
|
means any form of the work other than Source Code Form.
|
||||||
|
|
||||||
|
1.7. "Larger Work"
|
||||||
|
means a work that combines Covered Software with other material, in
|
||||||
|
a separate file or files, that is not Covered Software.
|
||||||
|
|
||||||
|
1.8. "License"
|
||||||
|
means this document.
|
||||||
|
|
||||||
|
1.9. "Licensable"
|
||||||
|
means having the right to grant, to the maximum extent possible,
|
||||||
|
whether at the time of the initial grant or subsequently, any and
|
||||||
|
all of the rights conveyed by this License.
|
||||||
|
|
||||||
|
1.10. "Modifications"
|
||||||
|
means any of the following:
|
||||||
|
|
||||||
|
(a) any file in Source Code Form that results from an addition to,
|
||||||
|
deletion from, or modification of the contents of Covered
|
||||||
|
Software; or
|
||||||
|
|
||||||
|
(b) any new file in Source Code Form that contains any Covered
|
||||||
|
Software.
|
||||||
|
|
||||||
|
1.11. "Patent Claims" of a Contributor
|
||||||
|
means any patent claim(s), including without limitation, method,
|
||||||
|
process, and apparatus claims, in any patent Licensable by such
|
||||||
|
Contributor that would be infringed, but for the grant of the
|
||||||
|
License, by the making, using, selling, offering for sale, having
|
||||||
|
made, import, or transfer of either its Contributions or its
|
||||||
|
Contributor Version.
|
||||||
|
|
||||||
|
1.12. "Secondary License"
|
||||||
|
means either the GNU General Public License, Version 2.0, the GNU
|
||||||
|
Lesser General Public License, Version 2.1, the GNU Affero General
|
||||||
|
Public License, Version 3.0, or any later versions of those
|
||||||
|
licenses.
|
||||||
|
|
||||||
|
1.13. "Source Code Form"
|
||||||
|
means the form of the work preferred for making modifications.
|
||||||
|
|
||||||
|
1.14. "You" (or "Your")
|
||||||
|
means an individual or a legal entity exercising rights under this
|
||||||
|
License. For legal entities, "You" includes any entity that
|
||||||
|
controls, is controlled by, or is under common control with You. For
|
||||||
|
purposes of this definition, "control" means (a) the power, direct
|
||||||
|
or indirect, to cause the direction or management of such entity,
|
||||||
|
whether by contract or otherwise, or (b) ownership of more than
|
||||||
|
fifty percent (50%) of the outstanding shares or beneficial
|
||||||
|
ownership of such entity.
|
||||||
|
|
||||||
|
2. License Grants and Conditions
|
||||||
|
--------------------------------
|
||||||
|
|
||||||
|
2.1. Grants
|
||||||
|
|
||||||
|
Each Contributor hereby grants You a world-wide, royalty-free,
|
||||||
|
non-exclusive license:
|
||||||
|
|
||||||
|
(a) under intellectual property rights (other than patent or trademark)
|
||||||
|
Licensable by such Contributor to use, reproduce, make available,
|
||||||
|
modify, display, perform, distribute, and otherwise exploit its
|
||||||
|
Contributions, either on an unmodified basis, with Modifications, or
|
||||||
|
as part of a Larger Work; and
|
||||||
|
|
||||||
|
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
||||||
|
for sale, have made, import, and otherwise transfer either its
|
||||||
|
Contributions or its Contributor Version.
|
||||||
|
|
||||||
|
2.2. Effective Date
|
||||||
|
|
||||||
|
The licenses granted in Section 2.1 with respect to any Contribution
|
||||||
|
become effective for each Contribution on the date the Contributor first
|
||||||
|
distributes such Contribution.
|
||||||
|
|
||||||
|
2.3. Limitations on Grant Scope
|
||||||
|
|
||||||
|
The licenses granted in this Section 2 are the only rights granted under
|
||||||
|
this License. No additional rights or licenses will be implied from the
|
||||||
|
distribution or licensing of Covered Software under this License.
|
||||||
|
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
||||||
|
Contributor:
|
||||||
|
|
||||||
|
(a) for any code that a Contributor has removed from Covered Software;
|
||||||
|
or
|
||||||
|
|
||||||
|
(b) for infringements caused by: (i) Your and any other third party's
|
||||||
|
modifications of Covered Software, or (ii) the combination of its
|
||||||
|
Contributions with other software (except as part of its Contributor
|
||||||
|
Version); or
|
||||||
|
|
||||||
|
(c) under Patent Claims infringed by Covered Software in the absence of
|
||||||
|
its Contributions.
|
||||||
|
|
||||||
|
This License does not grant any rights in the trademarks, service marks,
|
||||||
|
or logos of any Contributor (except as may be necessary to comply with
|
||||||
|
the notice requirements in Section 3.4).
|
||||||
|
|
||||||
|
2.4. Subsequent Licenses
|
||||||
|
|
||||||
|
No Contributor makes additional grants as a result of Your choice to
|
||||||
|
distribute the Covered Software under a subsequent version of this
|
||||||
|
License (see Section 10.2) or under the terms of a Secondary License (if
|
||||||
|
permitted under the terms of Section 3.3).
|
||||||
|
|
||||||
|
2.5. Representation
|
||||||
|
|
||||||
|
Each Contributor represents that the Contributor believes its
|
||||||
|
Contributions are its original creation(s) or it has sufficient rights
|
||||||
|
to grant the rights to its Contributions conveyed by this License.
|
||||||
|
|
||||||
|
2.6. Fair Use
|
||||||
|
|
||||||
|
This License is not intended to limit any rights You have under
|
||||||
|
applicable copyright doctrines of fair use, fair dealing, or other
|
||||||
|
equivalents.
|
||||||
|
|
||||||
|
2.7. Conditions
|
||||||
|
|
||||||
|
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
||||||
|
in Section 2.1.
|
||||||
|
|
||||||
|
3. Responsibilities
|
||||||
|
-------------------
|
||||||
|
|
||||||
|
3.1. Distribution of Source Form
|
||||||
|
|
||||||
|
All distribution of Covered Software in Source Code Form, including any
|
||||||
|
Modifications that You create or to which You contribute, must be under
|
||||||
|
the terms of this License. You must inform recipients that the Source
|
||||||
|
Code Form of the Covered Software is governed by the terms of this
|
||||||
|
License, and how they can obtain a copy of this License. You may not
|
||||||
|
attempt to alter or restrict the recipients' rights in the Source Code
|
||||||
|
Form.
|
||||||
|
|
||||||
|
3.2. Distribution of Executable Form
|
||||||
|
|
||||||
|
If You distribute Covered Software in Executable Form then:
|
||||||
|
|
||||||
|
(a) such Covered Software must also be made available in Source Code
|
||||||
|
Form, as described in Section 3.1, and You must inform recipients of
|
||||||
|
the Executable Form how they can obtain a copy of such Source Code
|
||||||
|
Form by reasonable means in a timely manner, at a charge no more
|
||||||
|
than the cost of distribution to the recipient; and
|
||||||
|
|
||||||
|
(b) You may distribute such Executable Form under the terms of this
|
||||||
|
License, or sublicense it under different terms, provided that the
|
||||||
|
license for the Executable Form does not attempt to limit or alter
|
||||||
|
the recipients' rights in the Source Code Form under this License.
|
||||||
|
|
||||||
|
3.3. Distribution of a Larger Work
|
||||||
|
|
||||||
|
You may create and distribute a Larger Work under terms of Your choice,
|
||||||
|
provided that You also comply with the requirements of this License for
|
||||||
|
the Covered Software. If the Larger Work is a combination of Covered
|
||||||
|
Software with a work governed by one or more Secondary Licenses, and the
|
||||||
|
Covered Software is not Incompatible With Secondary Licenses, this
|
||||||
|
License permits You to additionally distribute such Covered Software
|
||||||
|
under the terms of such Secondary License(s), so that the recipient of
|
||||||
|
the Larger Work may, at their option, further distribute the Covered
|
||||||
|
Software under the terms of either this License or such Secondary
|
||||||
|
License(s).
|
||||||
|
|
||||||
|
3.4. Notices
|
||||||
|
|
||||||
|
You may not remove or alter the substance of any license notices
|
||||||
|
(including copyright notices, patent notices, disclaimers of warranty,
|
||||||
|
or limitations of liability) contained within the Source Code Form of
|
||||||
|
the Covered Software, except that You may alter any license notices to
|
||||||
|
the extent required to remedy known factual inaccuracies.
|
||||||
|
|
||||||
|
3.5. Application of Additional Terms
|
||||||
|
|
||||||
|
You may choose to offer, and to charge a fee for, warranty, support,
|
||||||
|
indemnity or liability obligations to one or more recipients of Covered
|
||||||
|
Software. However, You may do so only on Your own behalf, and not on
|
||||||
|
behalf of any Contributor. You must make it absolutely clear that any
|
||||||
|
such warranty, support, indemnity, or liability obligation is offered by
|
||||||
|
You alone, and You hereby agree to indemnify every Contributor for any
|
||||||
|
liability incurred by such Contributor as a result of warranty, support,
|
||||||
|
indemnity or liability terms You offer. You may include additional
|
||||||
|
disclaimers of warranty and limitations of liability specific to any
|
||||||
|
jurisdiction.
|
||||||
|
|
||||||
|
4. Inability to Comply Due to Statute or Regulation
|
||||||
|
---------------------------------------------------
|
||||||
|
|
||||||
|
If it is impossible for You to comply with any of the terms of this
|
||||||
|
License with respect to some or all of the Covered Software due to
|
||||||
|
statute, judicial order, or regulation then You must: (a) comply with
|
||||||
|
the terms of this License to the maximum extent possible; and (b)
|
||||||
|
describe the limitations and the code they affect. Such description must
|
||||||
|
be placed in a text file included with all distributions of the Covered
|
||||||
|
Software under this License. Except to the extent prohibited by statute
|
||||||
|
or regulation, such description must be sufficiently detailed for a
|
||||||
|
recipient of ordinary skill to be able to understand it.
|
||||||
|
|
||||||
|
5. Termination
|
||||||
|
--------------
|
||||||
|
|
||||||
|
5.1. The rights granted under this License will terminate automatically
|
||||||
|
if You fail to comply with any of its terms. However, if You become
|
||||||
|
compliant, then the rights granted under this License from a particular
|
||||||
|
Contributor are reinstated (a) provisionally, unless and until such
|
||||||
|
Contributor explicitly and finally terminates Your grants, and (b) on an
|
||||||
|
ongoing basis, if such Contributor fails to notify You of the
|
||||||
|
non-compliance by some reasonable means prior to 60 days after You have
|
||||||
|
come back into compliance. Moreover, Your grants from a particular
|
||||||
|
Contributor are reinstated on an ongoing basis if such Contributor
|
||||||
|
notifies You of the non-compliance by some reasonable means, this is the
|
||||||
|
first time You have received notice of non-compliance with this License
|
||||||
|
from such Contributor, and You become compliant prior to 30 days after
|
||||||
|
Your receipt of the notice.
|
||||||
|
|
||||||
|
5.2. If You initiate litigation against any entity by asserting a patent
|
||||||
|
infringement claim (excluding declaratory judgment actions,
|
||||||
|
counter-claims, and cross-claims) alleging that a Contributor Version
|
||||||
|
directly or indirectly infringes any patent, then the rights granted to
|
||||||
|
You by any and all Contributors for the Covered Software under Section
|
||||||
|
2.1 of this License shall terminate.
|
||||||
|
|
||||||
|
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
|
||||||
|
end user license agreements (excluding distributors and resellers) which
|
||||||
|
have been validly granted by You or Your distributors under this License
|
||||||
|
prior to termination shall survive termination.
|
||||||
|
|
||||||
|
************************************************************************
|
||||||
|
* *
|
||||||
|
* 6. Disclaimer of Warranty *
|
||||||
|
* ------------------------- *
|
||||||
|
* *
|
||||||
|
* Covered Software is provided under this License on an "as is" *
|
||||||
|
* basis, without warranty of any kind, either expressed, implied, or *
|
||||||
|
* statutory, including, without limitation, warranties that the *
|
||||||
|
* Covered Software is free of defects, merchantable, fit for a *
|
||||||
|
* particular purpose or non-infringing. The entire risk as to the *
|
||||||
|
* quality and performance of the Covered Software is with You. *
|
||||||
|
* Should any Covered Software prove defective in any respect, You *
|
||||||
|
* (not any Contributor) assume the cost of any necessary servicing, *
|
||||||
|
* repair, or correction. This disclaimer of warranty constitutes an *
|
||||||
|
* essential part of this License. No use of any Covered Software is *
|
||||||
|
* authorized under this License except under this disclaimer. *
|
||||||
|
* *
|
||||||
|
************************************************************************
|
||||||
|
|
||||||
|
************************************************************************
|
||||||
|
* *
|
||||||
|
* 7. Limitation of Liability *
|
||||||
|
* -------------------------- *
|
||||||
|
* *
|
||||||
|
* Under no circumstances and under no legal theory, whether tort *
|
||||||
|
* (including negligence), contract, or otherwise, shall any *
|
||||||
|
* Contributor, or anyone who distributes Covered Software as *
|
||||||
|
* permitted above, be liable to You for any direct, indirect, *
|
||||||
|
* special, incidental, or consequential damages of any character *
|
||||||
|
* including, without limitation, damages for lost profits, loss of *
|
||||||
|
* goodwill, work stoppage, computer failure or malfunction, or any *
|
||||||
|
* and all other commercial damages or losses, even if such party *
|
||||||
|
* shall have been informed of the possibility of such damages. This *
|
||||||
|
* limitation of liability shall not apply to liability for death or *
|
||||||
|
* personal injury resulting from such party's negligence to the *
|
||||||
|
* extent applicable law prohibits such limitation. Some *
|
||||||
|
* jurisdictions do not allow the exclusion or limitation of *
|
||||||
|
* incidental or consequential damages, so this exclusion and *
|
||||||
|
* limitation may not apply to You. *
|
||||||
|
* *
|
||||||
|
************************************************************************
|
||||||
|
|
||||||
|
8. Litigation
|
||||||
|
-------------
|
||||||
|
|
||||||
|
Any litigation relating to this License may be brought only in the
|
||||||
|
courts of a jurisdiction where the defendant maintains its principal
|
||||||
|
place of business and such litigation shall be governed by laws of that
|
||||||
|
jurisdiction, without reference to its conflict-of-law provisions.
|
||||||
|
Nothing in this Section shall prevent a party's ability to bring
|
||||||
|
cross-claims or counter-claims.
|
||||||
|
|
||||||
|
9. Miscellaneous
|
||||||
|
----------------
|
||||||
|
|
||||||
|
This License represents the complete agreement concerning the subject
|
||||||
|
matter hereof. If any provision of this License is held to be
|
||||||
|
unenforceable, such provision shall be reformed only to the extent
|
||||||
|
necessary to make it enforceable. Any law or regulation which provides
|
||||||
|
that the language of a contract shall be construed against the drafter
|
||||||
|
shall not be used to construe this License against a Contributor.
|
||||||
|
|
||||||
|
10. Versions of the License
|
||||||
|
---------------------------
|
||||||
|
|
||||||
|
10.1. New Versions
|
||||||
|
|
||||||
|
Mozilla Foundation is the license steward. Except as provided in Section
|
||||||
|
10.3, no one other than the license steward has the right to modify or
|
||||||
|
publish new versions of this License. Each version will be given a
|
||||||
|
distinguishing version number.
|
||||||
|
|
||||||
|
10.2. Effect of New Versions
|
||||||
|
|
||||||
|
You may distribute the Covered Software under the terms of the version
|
||||||
|
of the License under which You originally received the Covered Software,
|
||||||
|
or under the terms of any subsequent version published by the license
|
||||||
|
steward.
|
||||||
|
|
||||||
|
10.3. Modified Versions
|
||||||
|
|
||||||
|
If you create software not governed by this License, and you want to
|
||||||
|
create a new license for such software, you may create and use a
|
||||||
|
modified version of this License if you rename the license and remove
|
||||||
|
any references to the name of the license steward (except to note that
|
||||||
|
such modified license differs from this License).
|
||||||
|
|
||||||
|
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
||||||
|
Licenses
|
||||||
|
|
||||||
|
If You choose to distribute Source Code Form that is Incompatible With
|
||||||
|
Secondary Licenses under the terms of this version of the License, the
|
||||||
|
notice described in Exhibit B of this License must be attached.
|
||||||
|
|
||||||
|
Exhibit A - Source Code Form License Notice
|
||||||
|
-------------------------------------------
|
||||||
|
|
||||||
|
This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
If it is not possible or desirable to put the notice in a particular
|
||||||
|
file, then You may include the notice in a location (such as a LICENSE
|
||||||
|
file in a relevant directory) where a recipient would be likely to look
|
||||||
|
for such a notice.
|
||||||
|
|
||||||
|
You may add additional accurate notices of copyright ownership.
|
||||||
|
|
||||||
|
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
||||||
|
---------------------------------------------------------
|
||||||
|
|
||||||
|
This Source Code Form is "Incompatible With Secondary Licenses", as
|
||||||
|
defined by the Mozilla Public License, v. 2.0.
|
||||||
+90
-34
@@ -4,40 +4,95 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"html/template"
|
"html/template"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os/exec"
|
"path"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"git.stephensearles.com/stephen/acedoc"
|
"git.stephensearles.com/stephen/acedoc"
|
||||||
"git.stephensearles.com/stephen/caddy-hugo2/comments"
|
"git.stephensearles.com/stephen/caddy-hugo2/comments"
|
||||||
|
"git.stephensearles.com/stephen/caddy-hugo2/media"
|
||||||
|
"go.uber.org/zap"
|
||||||
|
|
||||||
|
"github.com/caddyserver/caddy/v2"
|
||||||
|
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
|
||||||
|
"github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
|
||||||
|
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
|
||||||
"github.com/gohugoio/hugo/deps"
|
"github.com/gohugoio/hugo/deps"
|
||||||
"github.com/gohugoio/hugo/hugolib"
|
"github.com/gohugoio/hugo/hugolib"
|
||||||
"github.com/mholt/caddy"
|
|
||||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
|
||||||
"github.com/spf13/afero"
|
"github.com/spf13/afero"
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
plugin := CaddyHugo{}
|
caddy.RegisterModule(&CaddyHugo{})
|
||||||
|
httpcaddyfile.RegisterHandlerDirective("hugo", parseCaddyfile)
|
||||||
caddy.RegisterPlugin("hugo", caddy.Plugin{
|
|
||||||
ServerType: "http",
|
|
||||||
Action: plugin.SetupCaddy,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// CaddyHugo implements the plugin
|
type SiteConfig struct {
|
||||||
|
Hosts []string
|
||||||
|
Root string
|
||||||
|
CommentsEnabled bool
|
||||||
|
CommentsPassword string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *CaddyHugo) CaddyModule() caddy.ModuleInfo {
|
||||||
|
return caddy.ModuleInfo{
|
||||||
|
ID: "http.handlers.hugo",
|
||||||
|
New: func() caddy.Module { return new(CaddyHugo) },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *CaddyHugo) Provision(ctx caddy.Context) error {
|
||||||
|
m.logger = ctx.Logger(m)
|
||||||
|
|
||||||
|
if m.Site.CommentsEnabled {
|
||||||
|
m.Comments = comments.WithStorage(comments.NewDiskv(path.Join(m.Site.Root, "comments")))
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: not sure where m.Site is getting populated.
|
||||||
|
// m.Site.Root looks to be the working directory of caddy but it needs to be the directory of the site
|
||||||
|
root, err := filepath.Abs(m.Site.Root)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = m.Setup(root)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.OnCancel(func() {
|
||||||
|
m.persistAllEdits()
|
||||||
|
})
|
||||||
|
|
||||||
|
m.commentsSetting()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnmarshalCaddyfile implements caddyfile.Unmarshaler.
|
||||||
|
func (s *SiteConfig) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
|
||||||
|
for d.NextBlock(0) {
|
||||||
|
if d.Val() == "comments" {
|
||||||
|
if d.NextArg() {
|
||||||
|
s.CommentsPassword = d.Val()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CaddyHugo implements the plugin for a single site
|
||||||
type CaddyHugo struct {
|
type CaddyHugo struct {
|
||||||
|
logger *zap.Logger
|
||||||
|
|
||||||
ServerType string
|
ServerType string
|
||||||
Site *httpserver.SiteConfig
|
Site SiteConfig
|
||||||
HugoSites *hugolib.HugoSites
|
HugoSites *hugolib.HugoSites
|
||||||
HugoCfg *deps.DepsCfg
|
HugoCfg *deps.DepsCfg
|
||||||
|
|
||||||
Dir string
|
Dir string
|
||||||
|
|
||||||
Media *MediaSource
|
Media *media.MediaSource
|
||||||
Comments *comments.Service
|
Comments *comments.Service
|
||||||
|
|
||||||
docs map[string]*editSession
|
docs map[string]*editSession
|
||||||
@@ -49,14 +104,20 @@ type CaddyHugo struct {
|
|||||||
confirmingToClient map[uint64]struct{}
|
confirmingToClient map[uint64]struct{}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (ch *CaddyHugo) log(msg string, args ...interface{}) {
|
||||||
|
all := make([]any, len(args)+1)
|
||||||
|
all[0] = msg
|
||||||
|
copy(all[1:], args)
|
||||||
|
ch.logger.Info(fmt.Sprint(all...))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ch *CaddyHugo) logf(msg string, args ...interface{}) {
|
||||||
|
ch.logger.Info(fmt.Sprintf(msg, args...))
|
||||||
|
}
|
||||||
|
|
||||||
// Build rebuilds the cached state of the site. TODO: determine if this republishes
|
// Build rebuilds the cached state of the site. TODO: determine if this republishes
|
||||||
func (ch *CaddyHugo) Build() error {
|
func (ch *CaddyHugo) Build() error {
|
||||||
err := ch.HugoSites.Build(hugolib.BuildCfg{ResetState: true})
|
return buildSite(ch.HugoSites)
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("error building hugo sites: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// BasePath returns the directory that the CaddyHugo internal/author pages are under
|
// BasePath returns the directory that the CaddyHugo internal/author pages are under
|
||||||
@@ -73,22 +134,6 @@ func (ch *CaddyHugo) docFilename(orig string) string {
|
|||||||
return filepath.Join(ch.Dir, docname(orig))
|
return filepath.Join(ch.Dir, docname(orig))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Publish really renders new content into the public directory
|
|
||||||
func (ch *CaddyHugo) Publish() error {
|
|
||||||
err := ch.persistAllEdits()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
cmd := exec.Command("hugo")
|
|
||||||
cmd.Dir = ch.Dir
|
|
||||||
_, err = cmd.CombinedOutput()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// TmplData collects data for template execution
|
// TmplData collects data for template execution
|
||||||
func (ch *CaddyHugo) TmplData(r *http.Request, docref *editSession) interface{} {
|
func (ch *CaddyHugo) TmplData(r *http.Request, docref *editSession) interface{} {
|
||||||
var doc *acedoc.Document
|
var doc *acedoc.Document
|
||||||
@@ -102,3 +147,14 @@ func (ch *CaddyHugo) TmplData(r *http.Request, docref *editSession) interface{}
|
|||||||
}
|
}
|
||||||
return &tmplData{ch.Site, r, ch, doc, docref}
|
return &tmplData{ch.Site, r, ch, doc, docref}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// parseCaddyfile unmarshals tokens from h into a new Middleware.
|
||||||
|
func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) {
|
||||||
|
var m CaddyHugo
|
||||||
|
err := m.Site.UnmarshalCaddyfile(h.Dispenser)
|
||||||
|
return &m, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
_ caddy.Provisioner = (*CaddyHugo)(nil)
|
||||||
|
)
|
||||||
|
|||||||
@@ -38,11 +38,13 @@ func (ch *CaddyHugo) newEditSession(docName string) (*editSession, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
tmpfs := afero.NewCopyOnWriteFs(afero.NewOsFs(), afero.NewMemMapFs())
|
||||||
|
|
||||||
es := &editSession{
|
es := &editSession{
|
||||||
docname: docName,
|
docname: docName,
|
||||||
filename: filename,
|
filename: filename,
|
||||||
doc: acedoc.NewString(string(contents)),
|
doc: acedoc.NewString(string(contents)),
|
||||||
tmpfs: afero.NewCopyOnWriteFs(afero.NewOsFs(), afero.NewMemMapFs()),
|
tmpfs: tmpfs,
|
||||||
}
|
}
|
||||||
|
|
||||||
err = es.doc.LogToFile(path.Join(ch.Dir, "logs", docName))
|
err = es.doc.LogToFile(path.Join(ch.Dir, "logs", docName))
|
||||||
|
|||||||
+4
-3
@@ -64,10 +64,10 @@ func GetContent(siteRoot string, sites *hugolib.HugoSites) ([]Content, error) {
|
|||||||
page := sites.GetContentPage(fn)
|
page := sites.GetContentPage(fn)
|
||||||
if page != nil {
|
if page != nil {
|
||||||
files[i].Metadata = &Metadata{
|
files[i].Metadata = &Metadata{
|
||||||
Title: page.Title,
|
Title: page.Title(),
|
||||||
Path: file.Filename,
|
Path: file.Filename,
|
||||||
Date: page.Date,
|
Date: page.Date(),
|
||||||
Lastmod: page.Lastmod,
|
Lastmod: page.Lastmod(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -98,6 +98,7 @@ func (ch *CaddyHugo) NewContent(name, ctype string) (string, error) {
|
|||||||
if os.IsNotExist(err) {
|
if os.IsNotExist(err) {
|
||||||
cmd := exec.Command("hugo", "new", filename)
|
cmd := exec.Command("hugo", "new", filename)
|
||||||
cmd.Dir = ch.Dir
|
cmd.Dir = ch.Dir
|
||||||
|
ch.logf("running `hugo new` in %v", ch.Dir)
|
||||||
out, err := cmd.CombinedOutput()
|
out, err := cmd.CombinedOutput()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return filename, fmt.Errorf("error running 'hugo new': %v; %v", err, string(out))
|
return filename, fmt.Errorf("error running 'hugo new': %v; %v", err, string(out))
|
||||||
|
|||||||
@@ -35,16 +35,6 @@ func (ch *CaddyHugo) LTime() uint64 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (ch *CaddyHugo) ShouldApply(ltime uint64) bool {
|
func (ch *CaddyHugo) ShouldApply(ltime uint64) bool {
|
||||||
lowest := ch.LowestPendingConfirmation()
|
|
||||||
for _, c := range ch.Confirming() {
|
|
||||||
if lowest == 0 || c < lowest {
|
|
||||||
lowest = c
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ltime < lowest {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
ch.mtx.Lock()
|
ch.mtx.Lock()
|
||||||
defer ch.mtx.Unlock()
|
defer ch.mtx.Unlock()
|
||||||
@@ -56,12 +46,15 @@ func (ch *CaddyHugo) ShouldApply(ltime uint64) bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ConfirmLTime marks an ltime as something that should be confirmed with clients
|
||||||
func (ch *CaddyHugo) ConfirmLTime(ltime uint64) {
|
func (ch *CaddyHugo) ConfirmLTime(ltime uint64) {
|
||||||
ch.mtx.Lock()
|
ch.mtx.Lock()
|
||||||
defer ch.mtx.Unlock()
|
defer ch.mtx.Unlock()
|
||||||
ch.confirmingToClient[ltime] = struct{}{}
|
ch.confirmingToClient[ltime] = struct{}{}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Confirming returns the current list of LTimes that need to be confirmed
|
||||||
|
// to clients
|
||||||
func (ch *CaddyHugo) Confirming() []uint64 {
|
func (ch *CaddyHugo) Confirming() []uint64 {
|
||||||
var times []uint64
|
var times []uint64
|
||||||
|
|
||||||
@@ -74,6 +67,8 @@ func (ch *CaddyHugo) Confirming() []uint64 {
|
|||||||
return times
|
return times
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// LowestPendingConfirmation identifies the lowest LTime that needs to be
|
||||||
|
// confirmed to clients
|
||||||
func (ch *CaddyHugo) LowestPendingConfirmation() uint64 {
|
func (ch *CaddyHugo) LowestPendingConfirmation() uint64 {
|
||||||
var lowest uint64
|
var lowest uint64
|
||||||
for _, c := range ch.Confirming() {
|
for _, c := range ch.Confirming() {
|
||||||
@@ -95,7 +90,7 @@ func (ch *CaddyHugo) ClearConfirmed(lowestPending uint64) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ch *CaddyHugo) DeltaWebsocket(w http.ResponseWriter, r *http.Request) (int, error) {
|
func (ch *CaddyHugo) DeltaWebsocket(w http.ResponseWriter, r *http.Request) error {
|
||||||
var upgrader = websocket.Upgrader{
|
var upgrader = websocket.Upgrader{
|
||||||
ReadBufferSize: 1024,
|
ReadBufferSize: 1024,
|
||||||
WriteBufferSize: 1024,
|
WriteBufferSize: 1024,
|
||||||
@@ -104,7 +99,7 @@ func (ch *CaddyHugo) DeltaWebsocket(w http.ResponseWriter, r *http.Request) (int
|
|||||||
conn, err := upgrader.Upgrade(w, r, nil)
|
conn, err := upgrader.Upgrade(w, r, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
return http.StatusBadRequest, err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
conn.SetReadDeadline(time.Time{})
|
conn.SetReadDeadline(time.Time{})
|
||||||
@@ -112,7 +107,7 @@ func (ch *CaddyHugo) DeltaWebsocket(w http.ResponseWriter, r *http.Request) (int
|
|||||||
doc, err := ch.editSession(docNameFromEditRequest(r))
|
doc, err := ch.editSession(docNameFromEditRequest(r))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
return http.StatusBadRequest, err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return ch.handleDeltaConn(conn, doc)
|
return ch.handleDeltaConn(conn, doc)
|
||||||
@@ -127,7 +122,7 @@ func (ch *CaddyHugo) Message(deltas ...acedoc.Delta) Message {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ch *CaddyHugo) handleDeltaConn(conn DeltaConn, doc *editSession) (int, error) {
|
func (ch *CaddyHugo) handleDeltaConn(conn DeltaConn, doc *editSession) error {
|
||||||
const idlePing = 15 * time.Second
|
const idlePing = 15 * time.Second
|
||||||
const idlePingShort = 1 * time.Millisecond
|
const idlePingShort = 1 * time.Millisecond
|
||||||
|
|
||||||
@@ -181,10 +176,11 @@ func (ch *CaddyHugo) handleDeltaConn(conn DeltaConn, doc *editSession) (int, err
|
|||||||
errCh <- fmt.Errorf("error reading message from client conn: %v", err)
|
errCh <- fmt.Errorf("error reading message from client conn: %v", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ch.ObserveLTime(message.LTime)
|
if message.LTime != 0 {
|
||||||
|
ch.ObserveLTime(message.LTime)
|
||||||
|
}
|
||||||
|
|
||||||
if len(message.Deltas) == 0 {
|
if len(message.Deltas) == 0 {
|
||||||
time.Sleep(10 * time.Microsecond)
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -214,7 +210,7 @@ func (ch *CaddyHugo) handleDeltaConn(conn DeltaConn, doc *editSession) (int, err
|
|||||||
select {
|
select {
|
||||||
case err := <-errCh:
|
case err := <-errCh:
|
||||||
fmt.Println("error handling websocket connection:", err)
|
fmt.Println("error handling websocket connection:", err)
|
||||||
return 500, err
|
return err
|
||||||
default:
|
default:
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -227,7 +223,7 @@ func (ch *CaddyHugo) handleDeltaConn(conn DeltaConn, doc *editSession) (int, err
|
|||||||
case <-wroteMessagesCh:
|
case <-wroteMessagesCh:
|
||||||
resetTimer(idlePing)
|
resetTimer(idlePing)
|
||||||
case <-doneCh:
|
case <-doneCh:
|
||||||
return 200, nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+49
-115
@@ -1,10 +1,6 @@
|
|||||||
package caddyhugo
|
package caddyhugo
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
|
||||||
"io/ioutil"
|
|
||||||
"os"
|
|
||||||
"os/exec"
|
|
||||||
"path"
|
"path"
|
||||||
"sync"
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -13,136 +9,70 @@ import (
|
|||||||
"git.stephensearles.com/stephen/acedoc"
|
"git.stephensearles.com/stephen/acedoc"
|
||||||
)
|
)
|
||||||
|
|
||||||
type World struct {
|
|
||||||
CH *CaddyHugo
|
|
||||||
BlogFolder string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *World) Clean() {
|
|
||||||
if w.BlogFolder != "" {
|
|
||||||
os.RemoveAll(w.BlogFolder)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewWorld(t *testing.T) *World {
|
|
||||||
dir, err := ioutil.TempDir("", "caddy-hugo2-test-")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("error initializing test environment: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
w := &World{BlogFolder: dir}
|
|
||||||
|
|
||||||
cmd := exec.Command("hugo", "new", "site", dir)
|
|
||||||
cmd.Dir = dir
|
|
||||||
out, err := cmd.CombinedOutput()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("error initializing test site: %v\n\n%v", err, string(out))
|
|
||||||
}
|
|
||||||
|
|
||||||
w.CH = &CaddyHugo{}
|
|
||||||
w.CH.Setup(dir)
|
|
||||||
|
|
||||||
return w
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestEdits(t *testing.T) {
|
func TestEdits(t *testing.T) {
|
||||||
w := NewWorld(t)
|
w := NewWorld(t)
|
||||||
defer w.Clean()
|
defer w.Clean()
|
||||||
|
|
||||||
const title = "sometitle"
|
const title = "sometitle"
|
||||||
var contentPath = path.Join("content", title+".md")
|
|
||||||
|
|
||||||
|
var (
|
||||||
|
mtx sync.Mutex
|
||||||
|
|
||||||
|
contentPath = path.Join("content", title+".md")
|
||||||
|
|
||||||
|
// we will send these to the doc
|
||||||
|
send = []acedoc.Delta{
|
||||||
|
acedoc.Insert(0, 0, "hello"),
|
||||||
|
acedoc.Insert(0, 5, " world"),
|
||||||
|
acedoc.Insert(0, 11, " world"),
|
||||||
|
}
|
||||||
|
|
||||||
|
// we will use this to track what we get out of the doc
|
||||||
|
received = []acedoc.Delta{}
|
||||||
|
)
|
||||||
|
|
||||||
|
// prepare a new post
|
||||||
w.CH.NewContent(title, "")
|
w.CH.NewContent(title, "")
|
||||||
|
|
||||||
send := []acedoc.Delta{
|
// start an edit session
|
||||||
acedoc.Insert(0, 0, "hello"),
|
es, err := w.CH.editSession(contentPath)
|
||||||
acedoc.Insert(0, 5, " world"),
|
|
||||||
acedoc.Insert(0, 11, " world"),
|
|
||||||
}
|
|
||||||
var mtx sync.Mutex
|
|
||||||
received := []acedoc.Delta{}
|
|
||||||
|
|
||||||
doc, err := w.CH.editSession(contentPath)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal("error creating document client:", err)
|
t.Fatal("error creating document client:", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
doc.doc.Client(acedoc.DeltaHandlerFunc(func(ds []acedoc.Delta) error {
|
// register a client that we will use to push the deltas. we dont need
|
||||||
// receive some deltas...
|
// to actually do anything to receive deltas here, though.
|
||||||
|
c := es.doc.Client(acedoc.DeltaHandlerFunc(func(ds []acedoc.Delta) error {
|
||||||
|
return nil
|
||||||
|
}))
|
||||||
|
|
||||||
|
// register an *extra* client that just adds to the received delta
|
||||||
|
// slice we're tracking
|
||||||
|
es.doc.Client(acedoc.DeltaHandlerFunc(func(ds []acedoc.Delta) error {
|
||||||
mtx.Lock()
|
mtx.Lock()
|
||||||
defer mtx.Unlock()
|
defer mtx.Unlock()
|
||||||
received = append(received, ds...)
|
received = append(received, ds...)
|
||||||
return nil
|
return nil
|
||||||
}))
|
}))
|
||||||
|
|
||||||
|
// make sure we have an edit session
|
||||||
_, ok := w.CH.hasEditSession(contentPath)
|
_, ok := w.CH.hasEditSession(contentPath)
|
||||||
if !ok {
|
if !ok {
|
||||||
t.Fatal("expected there to be an established client")
|
t.Fatal("expected there to be an established client")
|
||||||
}
|
}
|
||||||
|
|
||||||
doc.doc.Apply(send...)
|
// push the deltas
|
||||||
|
c.PushDeltas(send...)
|
||||||
|
|
||||||
|
// wait...
|
||||||
<-time.After(5 * time.Second)
|
<-time.After(5 * time.Second)
|
||||||
|
|
||||||
|
// be sure we got the correct number of deltas back
|
||||||
mtx.Lock()
|
mtx.Lock()
|
||||||
defer mtx.Unlock()
|
defer mtx.Unlock()
|
||||||
if len(received) != len(send) {
|
if len(received) != len(send) {
|
||||||
t.Errorf("expected %d deltas, received %d; expected: %v, received: %v", len(send), len(received), send, received)
|
t.Errorf("expected %d deltas, received %d; expected: %v, received: %v", len(send), len(received), send, received)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
type WebsocketTester struct {
|
|
||||||
receivedPointer int
|
|
||||||
received [][]byte
|
|
||||||
wroteMessages []Message
|
|
||||||
wroteDeltas []acedoc.Delta
|
|
||||||
mtx sync.Mutex
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ws *WebsocketTester) ReadJSON(v interface{}) error {
|
|
||||||
ws.mtx.Lock()
|
|
||||||
defer ws.mtx.Unlock()
|
|
||||||
|
|
||||||
if len(ws.received) <= ws.receivedPointer {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
err := json.Unmarshal(ws.received[ws.receivedPointer], v)
|
|
||||||
ws.receivedPointer++
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ws *WebsocketTester) WriteJSON(v interface{}) error {
|
|
||||||
ws.mtx.Lock()
|
|
||||||
defer ws.mtx.Unlock()
|
|
||||||
|
|
||||||
m, ok := v.(Message)
|
|
||||||
if !ok {
|
|
||||||
panic("wrong type written to WebsocketTester")
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(m.Deltas) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
ws.wroteMessages = append(ws.wroteMessages, m)
|
|
||||||
ws.wroteDeltas = append(ws.wroteDeltas, m.Deltas...)
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ws *WebsocketTester) ReceiveJSON(v interface{}) error {
|
|
||||||
ws.mtx.Lock()
|
|
||||||
defer ws.mtx.Unlock()
|
|
||||||
|
|
||||||
out, err := json.Marshal(v)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
ws.received = append(ws.received, out)
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestDeltasSingle(t *testing.T) {
|
func TestDeltasSingle(t *testing.T) {
|
||||||
@@ -158,12 +88,12 @@ func TestDeltasSingle(t *testing.T) {
|
|||||||
|
|
||||||
client := new(WebsocketTester)
|
client := new(WebsocketTester)
|
||||||
|
|
||||||
doc, err := w.CH.editSession("content/" + title + ".md")
|
es, err := w.CH.editSession("content/" + title + ".md")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal("couldn't establish docref for client 0:", err)
|
t.Fatal("couldn't establish docref for client 0:", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
go w.CH.handleDeltaConn(client, doc)
|
go w.CH.handleDeltaConn(client, es)
|
||||||
|
|
||||||
a := acedoc.Insert(0, 0, "a")
|
a := acedoc.Insert(0, 0, "a")
|
||||||
|
|
||||||
@@ -174,9 +104,11 @@ func TestDeltasSingle(t *testing.T) {
|
|||||||
time.Sleep(50 * time.Millisecond)
|
time.Sleep(50 * time.Millisecond)
|
||||||
|
|
||||||
// we shouldn't have written back to the client,
|
// we shouldn't have written back to the client,
|
||||||
// so we expect to have written 0 messages
|
// so we expect to have written 0 *deltas*. (we may have written
|
||||||
if len(client.wroteMessages) != 0 {
|
// empty messages without deltas because of the pings to the client)
|
||||||
t.Errorf("client wrote %d messages, should have written %d", len(client.wroteMessages), 0)
|
if len(client.wroteDeltas) != 0 {
|
||||||
|
t.Errorf("client wrote %d deltas, should have written %d", len(client.wroteMessages), 0)
|
||||||
|
t.Logf("%v", client.wroteMessages)
|
||||||
}
|
}
|
||||||
|
|
||||||
// we received one, so make sure that's counted properly
|
// we received one, so make sure that's counted properly
|
||||||
@@ -217,7 +149,7 @@ func TestDeltasDouble(t *testing.T) {
|
|||||||
|
|
||||||
// so we expect clientA to have written 0 messages, and
|
// so we expect clientA to have written 0 messages, and
|
||||||
// clientB to have written 1
|
// clientB to have written 1
|
||||||
if len(clientA.wroteMessages) != 0 || len(clientB.wroteMessages) != 1 {
|
if len(clientA.wroteDeltas) != 0 || len(clientB.wroteDeltas) != 1 {
|
||||||
t.Errorf("clientA wrote %d messages, should have written 0. clientB wrote %d, should have written 1", len(clientA.wroteMessages), len(clientB.wroteMessages))
|
t.Errorf("clientA wrote %d messages, should have written 0. clientB wrote %d, should have written 1", len(clientA.wroteMessages), len(clientB.wroteMessages))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -238,9 +170,9 @@ func TestDeltasDouble(t *testing.T) {
|
|||||||
clientA.mtx.Lock()
|
clientA.mtx.Lock()
|
||||||
clientB.mtx.Lock()
|
clientB.mtx.Lock()
|
||||||
|
|
||||||
// so we expect clientA to have written 1 message this time, and
|
// so we expect clientA to have written 1 delta this time, and
|
||||||
// clientB to have written nothing new, so 1 still
|
// clientB to have written nothing new, so 1 still
|
||||||
if len(clientA.wroteMessages) != 1 || len(clientB.wroteMessages) != 1 {
|
if len(clientA.wroteDeltas) != 1 || len(clientB.wroteDeltas) != 1 {
|
||||||
t.Errorf("clientA wrote %d messages, should have written 1. clientB wrote %d, should have written 1 (just from before)", len(clientA.wroteMessages), len(clientB.wroteMessages))
|
t.Errorf("clientA wrote %d messages, should have written 1. clientB wrote %d, should have written 1 (just from before)", len(clientA.wroteMessages), len(clientB.wroteMessages))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -268,13 +200,15 @@ func TestDeltasMulti(t *testing.T) {
|
|||||||
|
|
||||||
doc, err := w.CH.editSession("content/" + title + ".md")
|
doc, err := w.CH.editSession("content/" + title + ".md")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal("couldn't establish docref:", err)
|
t.Fatal("couldn't establish edit session:", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
go w.CH.handleDeltaConn(clients[0], doc)
|
go w.CH.handleDeltaConn(clients[0], doc)
|
||||||
go w.CH.handleDeltaConn(clients[1], doc)
|
go w.CH.handleDeltaConn(clients[1], doc)
|
||||||
go w.CH.handleDeltaConn(clients[2], doc)
|
go w.CH.handleDeltaConn(clients[2], doc)
|
||||||
|
|
||||||
|
time.Sleep(100 * time.Millisecond)
|
||||||
|
|
||||||
a := acedoc.Insert(0, 0, "a")
|
a := acedoc.Insert(0, 0, "a")
|
||||||
b := acedoc.Insert(0, 0, "b")
|
b := acedoc.Insert(0, 0, "b")
|
||||||
c := acedoc.Insert(0, 0, "c")
|
c := acedoc.Insert(0, 0, "c")
|
||||||
@@ -283,12 +217,12 @@ func TestDeltasMulti(t *testing.T) {
|
|||||||
clients[1].ReceiveJSON(w.CH.Message(b))
|
clients[1].ReceiveJSON(w.CH.Message(b))
|
||||||
clients[2].ReceiveJSON(w.CH.Message(c))
|
clients[2].ReceiveJSON(w.CH.Message(c))
|
||||||
|
|
||||||
time.Sleep(400 * time.Millisecond)
|
time.Sleep(1000 * time.Millisecond)
|
||||||
|
|
||||||
for i, client := range clients {
|
for i, client := range clients {
|
||||||
client.mtx.Lock()
|
client.mtx.Lock()
|
||||||
// all clients should have "written" 2 deltas (could be the same
|
// all clients should have "written" 2 deltas out to their "browser"
|
||||||
// message) that came from the other clients
|
// that came from the other clients
|
||||||
if len(client.wroteDeltas) != 2 {
|
if len(client.wroteDeltas) != 2 {
|
||||||
t.Errorf("client %d wrote %d deltas, should have written 2", i, len(client.wroteDeltas))
|
t.Errorf("client %d wrote %d deltas, should have written 2", i, len(client.wroteDeltas))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package frontend
|
||||||
|
|
||||||
|
import "embed"
|
||||||
|
|
||||||
|
//go:embed templates
|
||||||
|
var templates embed.FS
|
||||||
|
|
||||||
|
func readFilename(filename string) string {
|
||||||
|
f, err := templates.ReadFile(filename)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return string(f)
|
||||||
|
}
|
||||||
|
|
||||||
|
func EditPage() string {
|
||||||
|
return readFilename("templates/edit.html.tmpl")
|
||||||
|
}
|
||||||
|
|
||||||
|
func AdminPage() string {
|
||||||
|
return readFilename("templates/admin.html.tmpl")
|
||||||
|
}
|
||||||
|
|
||||||
|
func AuthorPage() string {
|
||||||
|
return readFilename("templates/author.html.tmpl")
|
||||||
|
}
|
||||||
|
|
||||||
|
func UploadPage() string {
|
||||||
|
return readFilename("templates/upload.html.tmpl")
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
<html><body>not implemented</body></html>
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
{{ $timeFormat := "Jan _2 15:04:05" }}
|
||||||
|
<p>Create content:</p>
|
||||||
|
<form action="/hugo/edit/new" method="POST">
|
||||||
|
<label>Name: <input type="text" name="name" /></label>
|
||||||
|
<select name="type">
|
||||||
|
{{- range .ContentTypes }}
|
||||||
|
<option value="{{ . }}">{{ . }}</option>
|
||||||
|
{{- end }}
|
||||||
|
</select>
|
||||||
|
<input type="submit" />
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<p>Edit content:</p>
|
||||||
|
<table>{{ range .Content }}
|
||||||
|
<tr>
|
||||||
|
{{ if .Metadata }}
|
||||||
|
<td>
|
||||||
|
<a href="/hugo/edit/{{ .Filename }}">
|
||||||
|
{{ .Metadata.Title }}
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
{{ .Metadata.Date.Format $timeFormat }}
|
||||||
|
{{ if not (.Metadata.Lastmod.Equal .Metadata.Date) }}
|
||||||
|
(last modified {{.Metadata.Lastmod.Format $timeFormat }})
|
||||||
|
{{end}}
|
||||||
|
</td>
|
||||||
|
{{ else }}
|
||||||
|
<td>
|
||||||
|
<a href="/hugo/edit/{{ .Filename }}">
|
||||||
|
{{ .Filename }}
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>(unable to load metadata)</td>
|
||||||
|
{{ end }}
|
||||||
|
</tr>
|
||||||
|
{{- end }}
|
||||||
|
</table>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,316 @@
|
|||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<script src="/hugo/simplemde.js"></script>
|
||||||
|
<style type="text/css" media="screen">
|
||||||
|
#editor-wrapper {
|
||||||
|
position: absolute;
|
||||||
|
top: 50px;
|
||||||
|
right: 0;
|
||||||
|
bottom: 150px;
|
||||||
|
left: 40%;
|
||||||
|
}
|
||||||
|
#draft {
|
||||||
|
position: absolute;
|
||||||
|
top: 50px;
|
||||||
|
right: 60%;
|
||||||
|
bottom: 0;
|
||||||
|
left: 0;
|
||||||
|
|
||||||
|
}
|
||||||
|
#draft > iframe {
|
||||||
|
height: 100%;
|
||||||
|
width: 100%;
|
||||||
|
border: none;
|
||||||
|
}
|
||||||
|
a {
|
||||||
|
text-decoration: underline;
|
||||||
|
text-decoration-style: dotted;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
<link rel="stylesheet" href="/hugo/simplemde.css" />
|
||||||
|
<script src="/hugo/vue.js"></script>
|
||||||
|
<script src="/hugo/moment.js"></script>
|
||||||
|
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<div id="container" >
|
||||||
|
<div id="header">
|
||||||
|
<div id="lastSaved">
|
||||||
|
<span v-if="sendQueue.length > 0 || Object.keys(needConfirmation).length > 0">last saved ${ lastSaved.from(now) }, saving</span>
|
||||||
|
<span v-else>saved</span>
|
||||||
|
<span v-if="connectionError">, ${connectionError}</span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<a id="sideview-toggle-media">media</a>
|
||||||
|
<a id="sideview-toggle-draft">draft</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div id="editor-wrapper">
|
||||||
|
<textarea id="editor">{{ .LoadContent }}</textarea>
|
||||||
|
</div>
|
||||||
|
<div id="draft"><iframe src="{{ .IframeSource }}">Loading draft...</iframe></div>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
|
||||||
|
var iframe = document.querySelector("#draft > iframe");
|
||||||
|
|
||||||
|
document.onclick = function (event) {
|
||||||
|
var iframe = document.querySelector("#draft > iframe");
|
||||||
|
switch (event.target.id) {
|
||||||
|
case "sideview-toggle-media":
|
||||||
|
iframe.src = "/hugo/media";
|
||||||
|
break;
|
||||||
|
case "sideview-toggle-draft":
|
||||||
|
iframe.src = "{{ .IframeSource }}";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var uiBindings = {
|
||||||
|
ltime: {{ .LTime }},
|
||||||
|
serverLtime: 0,
|
||||||
|
lastSaved: moment(),
|
||||||
|
now: moment(),
|
||||||
|
connectionError: null,
|
||||||
|
sendQueue: [],
|
||||||
|
sentRecently: [],
|
||||||
|
needConfirmation: {},
|
||||||
|
};
|
||||||
|
|
||||||
|
var app = new Vue({
|
||||||
|
el: "#container",
|
||||||
|
data: uiBindings,
|
||||||
|
delimiters: ["${", "}"],
|
||||||
|
});
|
||||||
|
|
||||||
|
function getLtime() {
|
||||||
|
uiBindings.ltime++
|
||||||
|
return uiBindings.ltime
|
||||||
|
}
|
||||||
|
|
||||||
|
function observeServer(l, confirmed) {
|
||||||
|
uiBindings.serverLtime = l;
|
||||||
|
if (confirmed && confirmed.length > 0) {
|
||||||
|
confirmed.forEach(function (e) {
|
||||||
|
delete uiBindings.needConfirmation[e];
|
||||||
|
})
|
||||||
|
}
|
||||||
|
observe(l);
|
||||||
|
}
|
||||||
|
|
||||||
|
function observe(l) {
|
||||||
|
if (l > uiBindings.ltime) {
|
||||||
|
uiBindings.now = moment();
|
||||||
|
uiBindings.lastSaved = moment();
|
||||||
|
uiBindings.ltime = l;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var selectedImage;
|
||||||
|
var editorElem = document.getElementById("editor");
|
||||||
|
var editor = new SimpleMDE({
|
||||||
|
element: editorElem,
|
||||||
|
forceSync: true,
|
||||||
|
insertTexts: {
|
||||||
|
image: ["{\{% thumb filename=\"", "#url#\" width=\"200\" %}}"]
|
||||||
|
},
|
||||||
|
imageURLFn: function () {
|
||||||
|
return selectedImage;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
window.onmessage = function (evt) {
|
||||||
|
selectedImage = evt.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Create WebSocket connection.
|
||||||
|
var socket = connect();
|
||||||
|
|
||||||
|
|
||||||
|
const sawChangesBumpsTo = 10;
|
||||||
|
|
||||||
|
var sentinelSrc = 'about:blank';
|
||||||
|
var oldSrc = '';
|
||||||
|
|
||||||
|
var sawChanges = -1;
|
||||||
|
window.setInterval(function () {
|
||||||
|
if (sawChanges >= 0) {
|
||||||
|
sawChanges--;
|
||||||
|
if (sawChanges == 0) {
|
||||||
|
if (iframe.contentWindow) {
|
||||||
|
iframe.contentWindow.location.reload();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
uiBindings.now = moment();
|
||||||
|
if (uiBindings.connectionError) {
|
||||||
|
socket = connect();
|
||||||
|
} else if (uiBindings.sendQueue.length > 0) {
|
||||||
|
var ltime = getLtime();
|
||||||
|
|
||||||
|
// record lowest pending
|
||||||
|
// ltime at the time this message
|
||||||
|
// was serialized
|
||||||
|
var lowestPending = ltime;
|
||||||
|
for (c in uiBindings.needConfirmation) {
|
||||||
|
c = parseInt(c, 10);
|
||||||
|
if (lowestPending === 0 || c < lowestPending) {
|
||||||
|
lowestPending = c;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var msg = JSON.stringify({
|
||||||
|
"deltas": uiBindings.sendQueue,
|
||||||
|
"ltime": ltime,
|
||||||
|
"lowestPending": lowestPending,
|
||||||
|
});
|
||||||
|
uiBindings.sendQueue = [];
|
||||||
|
uiBindings.needConfirmation[ltime] = msg;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (ltime in uiBindings.needConfirmation) {
|
||||||
|
var msg = uiBindings.needConfirmation[ltime];
|
||||||
|
socket.send(msg);
|
||||||
|
}
|
||||||
|
}, 500);
|
||||||
|
|
||||||
|
function connect() {
|
||||||
|
const socket = new WebSocket((location.protocol == "https:" ? 'wss://' : 'ws://') + location.host + location.pathname);
|
||||||
|
|
||||||
|
// Listen for messages
|
||||||
|
socket.addEventListener('message', function (event) {
|
||||||
|
var message = JSON.parse(event.data);
|
||||||
|
observeServer(message.ltime, message.confirmed);
|
||||||
|
|
||||||
|
var deltas = [];
|
||||||
|
deltas.push.apply(deltas, message.deltas);
|
||||||
|
|
||||||
|
deltas.forEach(function(aceDelta) {
|
||||||
|
var cmDelta = aceDeltaToCM(aceDelta)
|
||||||
|
|
||||||
|
var content = ""
|
||||||
|
var to = {
|
||||||
|
line: aceDelta.start.row,
|
||||||
|
ch: aceDelta.start.column,
|
||||||
|
}
|
||||||
|
|
||||||
|
if (aceDelta.action == "insert") {
|
||||||
|
content = aceDelta.lines.join("\n");
|
||||||
|
to = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
editor.codemirror.doc.replaceRange(content, cmDelta.from, to, "dontreflect");
|
||||||
|
sawChanges = sawChangesBumpsTo;
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.addEventListener('open', function () {
|
||||||
|
uiBindings.connectionError = null;
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.addEventListener('close', function () {
|
||||||
|
if (!uiBindings.connectionError) {
|
||||||
|
getLtime();
|
||||||
|
uiBindings.connectionError = "server connection closed, reconnecting...";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.addEventListener('error', function (err) {
|
||||||
|
if (!uiBindings.connectionError) {
|
||||||
|
uiBindings.connectionError = err;
|
||||||
|
getLtime();
|
||||||
|
}
|
||||||
|
console.log(err);
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
return socket;
|
||||||
|
}
|
||||||
|
|
||||||
|
editor.codemirror.on("change", function (cm, cmDelta) {
|
||||||
|
if (cmDelta.origin == "dontreflect") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var aceDelta = cmDeltaToAce(cmDelta);
|
||||||
|
console.log(cmDelta, "=>", aceDelta)
|
||||||
|
|
||||||
|
sawChanges = sawChangesBumpsTo;
|
||||||
|
uiBindings.sendQueue.push.apply(uiBindings.sendQueue, aceDelta);
|
||||||
|
})
|
||||||
|
|
||||||
|
function cmDeltaToAce(cmDelta) {
|
||||||
|
var isRemove = (cmDelta.removed.length > 0 && cmDelta.removed[0].length > 0) || cmDelta.removed.length > 1;
|
||||||
|
var lines = isRemove ? cmDelta.removed : cmDelta.text;
|
||||||
|
var aceDelta = {
|
||||||
|
action: isRemove ? "remove" : "insert",
|
||||||
|
lines: lines,
|
||||||
|
start: {
|
||||||
|
row: cmDelta.from.line,
|
||||||
|
column: cmDelta.from.ch,
|
||||||
|
},
|
||||||
|
end: {
|
||||||
|
row: cmDelta.from.line + (isRemove ? lines.length - 1 : lines.length - 1 ),
|
||||||
|
column: lines[lines.length-1].length,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (aceDelta.start.row == aceDelta.end.row) {
|
||||||
|
aceDelta.end.column += cmDelta.from.ch;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (false && isRemove && aceDelta.start.row == aceDelta.end.row) {
|
||||||
|
var origStart = aceDelta.start;
|
||||||
|
aceDelta.start = aceDelta.end;
|
||||||
|
aceDelta.end = origStart;
|
||||||
|
aceDelta.start.column += cmDelta.from.ch;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isRemove && ((cmDelta.text.length > 0 && cmDelta.text[0].length > 0) || cmDelta.text.length > 1)) {
|
||||||
|
cmDelta.removed = [""];
|
||||||
|
var ret = [aceDelta];
|
||||||
|
ret.push.apply(ret, cmDeltaToAce(cmDelta));
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [aceDelta];
|
||||||
|
}
|
||||||
|
|
||||||
|
function aceDeltaToCM(aceDelta) {
|
||||||
|
|
||||||
|
var cmDelta = {
|
||||||
|
text: [],
|
||||||
|
removed: [],
|
||||||
|
from: {
|
||||||
|
line: aceDelta.start.row,
|
||||||
|
ch: aceDelta.start.column,
|
||||||
|
},
|
||||||
|
to: {
|
||||||
|
// cm deltas are weird. to refers to the selection end, which
|
||||||
|
// with a simple blinking cursor with no selection, is always
|
||||||
|
// the same as from
|
||||||
|
line: aceDelta.start.row,
|
||||||
|
ch: aceDelta.start.column,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
if (aceDelta.action == "remove") {
|
||||||
|
var origStart = aceDelta.start;
|
||||||
|
aceDelta.start = aceDelta.end;
|
||||||
|
aceDelta.end = origStart;
|
||||||
|
|
||||||
|
cmDelta.removed = aceDelta.lines
|
||||||
|
cmDelta.text = [""]
|
||||||
|
} else {
|
||||||
|
cmDelta.text = aceDelta.lines
|
||||||
|
cmDelta.removed = [""]
|
||||||
|
}
|
||||||
|
|
||||||
|
return cmDelta;
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
<input type="file" style="display: hidden;" id="{{.ElemName}}" />
|
||||||
|
<div id="{{.ElemName}}_dropzone" ondrop="dropHandler(event);" ondragover="draghandler(event);" ondragenter="draghandler(event);" ondragleave="draghandler(event);" style="background-color: rgba(0,0,0,0.5); visibility: hidden; opacity:0; position: fixed; top: 0; bottom: 0; left: 0; right: 0; width: 100%; height: 100%; ; transition: visibility 175ms, opacity 175ms; z-index: 9999999;"></div>
|
||||||
|
<script>
|
||||||
|
document.addEventListener("DOMContentLoaded", function () {
|
||||||
|
var fileInput = document.getElementById('{{.ElemName}}');
|
||||||
|
var dropzone = document.getElementById('{{.ElemName}}_dropzone');
|
||||||
|
|
||||||
|
fileInput.onchange = function () {
|
||||||
|
var formData = new FormData();
|
||||||
|
fileInput.files.forEach(function (file) {
|
||||||
|
formData.append(file.name, file);
|
||||||
|
});
|
||||||
|
upload(formData);
|
||||||
|
}
|
||||||
|
|
||||||
|
var lastTarget = null;
|
||||||
|
|
||||||
|
window.addEventListener("dragenter", function(e)
|
||||||
|
{
|
||||||
|
lastTarget = e.target; // cache the last target here
|
||||||
|
// unhide our dropzone overlay
|
||||||
|
dropzone.style.visibility = "";
|
||||||
|
dropzone.style.opacity = 1;
|
||||||
|
});
|
||||||
|
|
||||||
|
window.addEventListener("dragleave", function(e)
|
||||||
|
{
|
||||||
|
// this is the magic part. when leaving the window,
|
||||||
|
// e.target happens to be exactly what we want: what we cached
|
||||||
|
// at the start, the dropzone we dragged into.
|
||||||
|
// so..if dragleave target matches our cache, we hide the dropzone.
|
||||||
|
if(e.target === lastTarget)
|
||||||
|
{
|
||||||
|
dropzone.style.visibility = "hidden";
|
||||||
|
dropzone.style.opacity = 0;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
function draghandler(evt) {
|
||||||
|
evt.preventDefault();
|
||||||
|
}
|
||||||
|
|
||||||
|
function dropHandler(evt) {
|
||||||
|
evt.preventDefault();
|
||||||
|
|
||||||
|
var files = evt.dataTransfer.files;
|
||||||
|
var formData = new FormData();
|
||||||
|
|
||||||
|
for (var i = 0; i < files.length; i++) {
|
||||||
|
formData.append(files[i].name, files[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
upload(formData);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function upload(formData) {
|
||||||
|
var xhr = new XMLHttpRequest();
|
||||||
|
xhr.onreadystatechange = function(e) {
|
||||||
|
if ( 4 == this.readyState ) {
|
||||||
|
window.location.reload(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
xhr.open('POST', '/hugo/upload');
|
||||||
|
xhr.send(formData);
|
||||||
|
}
|
||||||
|
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
module git.stephensearles.com/stephen/caddy-hugo2
|
||||||
|
|
||||||
|
go 1.18
|
||||||
|
|
||||||
|
require (
|
||||||
|
git.stephensearles.com/stephen/acedoc v0.0.0-20170928122432-96da2793a59d
|
||||||
|
git.stephensearles.com/stephen/idleshut v0.0.0-20180107224249-cde7779f51c8
|
||||||
|
github.com/PuerkitoBio/goquery v1.5.0
|
||||||
|
github.com/caddyserver/caddy/v2 v2.1.1
|
||||||
|
github.com/caddyserver/xcaddy v0.3.0
|
||||||
|
github.com/gohugoio/hugo v0.74.4-0.20200822075643-d39636a5fc6b
|
||||||
|
github.com/gorilla/websocket v1.4.1
|
||||||
|
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646
|
||||||
|
github.com/peterbourgon/diskv v2.0.1+incompatible
|
||||||
|
github.com/spf13/afero v1.2.2
|
||||||
|
github.com/spf13/viper v1.6.1
|
||||||
|
github.com/tajtiattila/metadata v0.0.0-20180130123038-1ef25f4c37ea
|
||||||
|
go.uber.org/zap v1.15.0
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
cloud.google.com/go v0.54.0 // indirect
|
||||||
|
github.com/AndreasBriese/bbloom v0.0.0-20190306092124-e2d15f34fcf9 // indirect
|
||||||
|
github.com/BurntSushi/locker v0.0.0-20171006230638-a6e239ea1c69 // indirect
|
||||||
|
github.com/BurntSushi/toml v0.3.1 // indirect
|
||||||
|
github.com/DataDog/zstd v1.4.1 // indirect
|
||||||
|
github.com/Masterminds/goutils v1.1.0 // indirect
|
||||||
|
github.com/Masterminds/semver/v3 v3.1.1 // indirect
|
||||||
|
github.com/Masterminds/sprig/v3 v3.1.0 // indirect
|
||||||
|
github.com/PuerkitoBio/purell v1.1.1 // indirect
|
||||||
|
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect
|
||||||
|
github.com/alecthomas/chroma v0.8.0 // indirect
|
||||||
|
github.com/andybalholm/cascadia v1.0.0 // indirect
|
||||||
|
github.com/antlr/antlr4 v0.0.0-20200503195918-621b933c7a7f // indirect
|
||||||
|
github.com/armon/go-radix v1.0.0 // indirect
|
||||||
|
github.com/bep/debounce v1.2.0 // indirect
|
||||||
|
github.com/bep/gitmap v1.1.2 // indirect
|
||||||
|
github.com/bep/golibsass v0.6.0 // indirect
|
||||||
|
github.com/bep/tmc v0.5.1 // indirect
|
||||||
|
github.com/caddyserver/certmagic v0.11.2 // indirect
|
||||||
|
github.com/cenkalti/backoff/v4 v4.0.0 // indirect
|
||||||
|
github.com/cespare/xxhash v1.1.0 // indirect
|
||||||
|
github.com/cheekybits/genny v1.0.0 // indirect
|
||||||
|
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e // indirect
|
||||||
|
github.com/cpuguy83/go-md2man/v2 v2.0.0 // indirect
|
||||||
|
github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964 // indirect
|
||||||
|
github.com/dgraph-io/badger v1.5.3 // indirect
|
||||||
|
github.com/dgraph-io/badger/v2 v2.0.1-rc1.0.20200413122845-09dd2e1a4195 // indirect
|
||||||
|
github.com/dgraph-io/ristretto v0.0.2-0.20200115201040-8f368f2f2ab3 // indirect
|
||||||
|
github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2 // indirect
|
||||||
|
github.com/disintegration/gift v1.2.1 // indirect
|
||||||
|
github.com/dlclark/regexp2 v1.2.0 // indirect
|
||||||
|
github.com/dustin/go-humanize v1.0.1-0.20200219035652-afde56e7acac // indirect
|
||||||
|
github.com/evanw/esbuild v0.6.5 // indirect
|
||||||
|
github.com/fsnotify/fsnotify v1.4.9 // indirect
|
||||||
|
github.com/getkin/kin-openapi v0.14.0 // indirect
|
||||||
|
github.com/ghodss/yaml v1.0.0 // indirect
|
||||||
|
github.com/go-acme/lego/v3 v3.7.0 // indirect
|
||||||
|
github.com/go-sql-driver/mysql v1.5.0 // indirect
|
||||||
|
github.com/gobuffalo/envy v1.7.0 // indirect
|
||||||
|
github.com/gobwas/glob v0.2.3 // indirect
|
||||||
|
github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e // indirect
|
||||||
|
github.com/golang/protobuf v1.4.2 // indirect
|
||||||
|
github.com/golang/snappy v0.0.1 // indirect
|
||||||
|
github.com/google/btree v1.0.0 // indirect
|
||||||
|
github.com/google/cel-go v0.5.1 // indirect
|
||||||
|
github.com/google/go-cmp v0.5.0 // indirect
|
||||||
|
github.com/google/uuid v1.1.1 // indirect
|
||||||
|
github.com/googleapis/gax-go/v2 v2.0.5 // indirect
|
||||||
|
github.com/hashicorp/hcl v1.0.0 // indirect
|
||||||
|
github.com/huandu/xstrings v1.3.1 // indirect
|
||||||
|
github.com/imdario/mergo v0.3.8 // indirect
|
||||||
|
github.com/jdkato/prose v1.1.1 // indirect
|
||||||
|
github.com/joho/godotenv v1.3.0 // indirect
|
||||||
|
github.com/juju/ansiterm v0.0.0-20180109212912-720a0952cc2a // indirect
|
||||||
|
github.com/klauspost/cpuid v1.3.0 // indirect
|
||||||
|
github.com/kyokomi/emoji v2.2.1+incompatible // indirect
|
||||||
|
github.com/libdns/libdns v0.0.0-20200501023120-186724ffc821 // indirect
|
||||||
|
github.com/lucas-clemente/quic-go v0.18.0 // indirect
|
||||||
|
github.com/lunixbochs/vtclean v1.0.0 // indirect
|
||||||
|
github.com/magiconair/properties v1.8.1 // indirect
|
||||||
|
github.com/manifoldco/promptui v0.3.1 // indirect
|
||||||
|
github.com/markbates/inflect v1.0.0 // indirect
|
||||||
|
github.com/marten-seemann/qpack v0.2.0 // indirect
|
||||||
|
github.com/marten-seemann/qtls v0.10.0 // indirect
|
||||||
|
github.com/marten-seemann/qtls-go1-15 v0.1.0 // indirect
|
||||||
|
github.com/mattn/go-colorable v0.1.6 // indirect
|
||||||
|
github.com/mattn/go-isatty v0.0.12 // indirect
|
||||||
|
github.com/mattn/go-runewidth v0.0.7 // indirect
|
||||||
|
github.com/miekg/dns v1.1.30 // indirect
|
||||||
|
github.com/miekg/mmark v1.3.6 // indirect
|
||||||
|
github.com/mitchellh/copystructure v1.0.0 // indirect
|
||||||
|
github.com/mitchellh/hashstructure v1.0.0 // indirect
|
||||||
|
github.com/mitchellh/mapstructure v1.1.2 // indirect
|
||||||
|
github.com/mitchellh/reflectwalk v1.0.0 // indirect
|
||||||
|
github.com/muesli/smartcrop v0.3.0 // indirect
|
||||||
|
github.com/nicksnyder/go-i18n v1.10.0 // indirect
|
||||||
|
github.com/niklasfasching/go-org v1.3.1 // indirect
|
||||||
|
github.com/olekukonko/tablewriter v0.0.4 // indirect
|
||||||
|
github.com/pelletier/go-toml v1.6.0 // indirect
|
||||||
|
github.com/pkg/errors v0.9.1 // indirect
|
||||||
|
github.com/rogpeppe/go-internal v1.5.1 // indirect
|
||||||
|
github.com/russross/blackfriday v1.5.3-0.20200218234912-41c5fccfd6f6 // indirect
|
||||||
|
github.com/russross/blackfriday/v2 v2.0.1 // indirect
|
||||||
|
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd // indirect
|
||||||
|
github.com/samfoo/ansi v0.0.0-20160124022901-b6bd2ded7189 // indirect
|
||||||
|
github.com/sanity-io/litter v1.2.0 // indirect
|
||||||
|
github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect
|
||||||
|
github.com/smallstep/certificates v0.15.0-rc.1.0.20200506212953-e855707dc274 // indirect
|
||||||
|
github.com/smallstep/cli v0.14.4 // indirect
|
||||||
|
github.com/smallstep/nosql v0.3.0 // indirect
|
||||||
|
github.com/smallstep/truststore v0.9.5 // indirect
|
||||||
|
github.com/spf13/cast v1.3.1 // indirect
|
||||||
|
github.com/spf13/jwalterweatherman v1.1.0 // indirect
|
||||||
|
github.com/spf13/pflag v1.0.5 // indirect
|
||||||
|
github.com/subosito/gotenv v1.2.0 // indirect
|
||||||
|
github.com/tdewolff/minify/v2 v2.6.2 // indirect
|
||||||
|
github.com/tdewolff/parse/v2 v2.4.2 // indirect
|
||||||
|
github.com/urfave/cli v1.22.2 // indirect
|
||||||
|
github.com/yuin/goldmark v1.1.32 // indirect
|
||||||
|
github.com/yuin/goldmark-highlighting v0.0.0-20200307114337-60d527fdb691 // indirect
|
||||||
|
go.etcd.io/bbolt v1.3.2 // indirect
|
||||||
|
go.opencensus.io v0.22.3 // indirect
|
||||||
|
go.uber.org/atomic v1.6.0 // indirect
|
||||||
|
go.uber.org/multierr v1.5.0 // indirect
|
||||||
|
golang.org/x/crypto v0.0.0-20200728195943-123391ffb6de // indirect
|
||||||
|
golang.org/x/image v0.0.0-20191214001246-9130b4cfad52 // indirect
|
||||||
|
golang.org/x/net v0.0.0-20200707034311-ab3426394381 // indirect
|
||||||
|
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d // indirect
|
||||||
|
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e // indirect
|
||||||
|
golang.org/x/sys v0.0.0-20200519105757-fe76b779f299 // indirect
|
||||||
|
golang.org/x/text v0.3.2 // indirect
|
||||||
|
google.golang.org/api v0.20.0 // indirect
|
||||||
|
google.golang.org/appengine v1.6.5 // indirect
|
||||||
|
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013 // indirect
|
||||||
|
google.golang.org/grpc v1.27.1 // indirect
|
||||||
|
google.golang.org/protobuf v1.25.0 // indirect
|
||||||
|
gopkg.in/ini.v1 v1.51.1 // indirect
|
||||||
|
gopkg.in/square/go-jose.v2 v2.4.0 // indirect
|
||||||
|
gopkg.in/yaml.v2 v2.3.0 // indirect
|
||||||
|
howett.net/plist v0.0.0-20200419221736-3b63eb3a43b5 // indirect
|
||||||
|
)
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
package caddyhugo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"io/ioutil"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.stephensearles.com/stephen/acedoc"
|
||||||
|
)
|
||||||
|
|
||||||
|
type World struct {
|
||||||
|
CH *CaddyHugo
|
||||||
|
BlogFolder string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *World) Clean() {
|
||||||
|
if w.BlogFolder != "" {
|
||||||
|
os.RemoveAll(w.BlogFolder)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewWorld(t *testing.T) *World {
|
||||||
|
dir, err := ioutil.TempDir("", "caddy-hugo2-test-")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("error initializing test environment: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
w := &World{BlogFolder: dir}
|
||||||
|
|
||||||
|
cmd := exec.Command("hugo", "new", "site", dir)
|
||||||
|
cmd.Dir = dir
|
||||||
|
out, err := cmd.CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("error initializing test site: %v\n\n%v", err, string(out))
|
||||||
|
}
|
||||||
|
|
||||||
|
w.CH = &CaddyHugo{}
|
||||||
|
w.CH.Setup(dir)
|
||||||
|
|
||||||
|
return w
|
||||||
|
}
|
||||||
|
|
||||||
|
type WebsocketTester struct {
|
||||||
|
receivedPointer int
|
||||||
|
received [][]byte
|
||||||
|
wroteMessages []Message
|
||||||
|
wroteDeltas []acedoc.Delta
|
||||||
|
mtx sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReadJSON reads the next pending message from the "client" into v
|
||||||
|
func (ws *WebsocketTester) ReadJSON(v interface{}) error {
|
||||||
|
ws.mtx.Lock()
|
||||||
|
defer ws.mtx.Unlock()
|
||||||
|
|
||||||
|
if len(ws.received) <= ws.receivedPointer {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
err := json.Unmarshal(ws.received[ws.receivedPointer], v)
|
||||||
|
ws.receivedPointer++
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// WriteJSON "sends" a message, v, to the "client"
|
||||||
|
func (ws *WebsocketTester) WriteJSON(v interface{}) error {
|
||||||
|
ws.mtx.Lock()
|
||||||
|
defer ws.mtx.Unlock()
|
||||||
|
|
||||||
|
m, ok := v.(Message)
|
||||||
|
if !ok {
|
||||||
|
panic("wrong type written to WebsocketTester")
|
||||||
|
}
|
||||||
|
|
||||||
|
ws.wroteMessages = append(ws.wroteMessages, m)
|
||||||
|
ws.wroteDeltas = append(ws.wroteDeltas, m.Deltas...)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReceiveJSON queues a message to be sent to the client
|
||||||
|
func (ws *WebsocketTester) ReceiveJSON(v interface{}) error {
|
||||||
|
ws.mtx.Lock()
|
||||||
|
defer ws.mtx.Unlock()
|
||||||
|
|
||||||
|
out, err := json.Marshal(v)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
ws.received = append(ws.received, out)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -2,7 +2,9 @@ package caddyhugo
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
@@ -10,26 +12,25 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"git.stephensearles.com/stephen/caddy-hugo2/assets"
|
"git.stephensearles.com/stephen/caddy-hugo2/assets"
|
||||||
"github.com/mholt/caddy"
|
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
|
||||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
|
||||||
"github.com/spf13/afero"
|
"github.com/spf13/afero"
|
||||||
)
|
)
|
||||||
|
|
||||||
func (ch *CaddyHugo) ServeHTTPWithNext(next httpserver.Handler, c *caddy.Controller, w http.ResponseWriter, r *http.Request) (int, error) {
|
func (ch *CaddyHugo) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
|
||||||
if !ch.Match(r) {
|
if !ch.Match(r) {
|
||||||
p := path.Join(ch.Dir, "public", r.URL.Path)
|
p := path.Join(ch.Dir, "public", r.URL.Path)
|
||||||
http.ServeFile(w, r, p)
|
http.ServeFile(w, r, p)
|
||||||
return 200, nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if ch.Comments != nil && strings.HasSuffix(r.URL.Path, "/comments") {
|
if ch.Comments != nil && strings.HasSuffix(r.URL.Path, "/comments") {
|
||||||
docName := docNameFromCommentRequest(r)
|
docName := docNameFromCommentRequest(r)
|
||||||
err := ch.Comments.ServeComments(docName, w, r)
|
err := ch.Comments.ServeComments(docName, w, r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 500, fmt.Errorf("couldn't load comments:", err)
|
return fmt.Errorf("couldn't load comments:", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return 200, nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if r.URL.Path == "/login" {
|
if r.URL.Path == "/login" {
|
||||||
@@ -39,32 +40,31 @@ func (ch *CaddyHugo) ServeHTTPWithNext(next httpserver.Handler, c *caddy.Control
|
|||||||
if strings.HasPrefix(r.URL.Path, "/hugo/publish") {
|
if strings.HasPrefix(r.URL.Path, "/hugo/publish") {
|
||||||
err := ch.Publish()
|
err := ch.Publish()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
return err
|
||||||
return http.StatusInternalServerError, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
http.Redirect(w, r, "/", http.StatusFound)
|
http.Redirect(w, r, "/", http.StatusFound)
|
||||||
return http.StatusFound, nil
|
return nil
|
||||||
}
|
}
|
||||||
if strings.HasPrefix(r.URL.Path, "/hugo/simplemde.css") {
|
if strings.HasPrefix(r.URL.Path, "/hugo/simplemde.css") {
|
||||||
w.Write(assets.MustAsset("simplemde/dist/simplemde.min.css"))
|
w.Write(assets.MustAsset("simplemde/dist/simplemde.min.css"))
|
||||||
return http.StatusOK, nil
|
return nil
|
||||||
}
|
}
|
||||||
if strings.HasPrefix(r.URL.Path, "/hugo/simplemde.js") {
|
if strings.HasPrefix(r.URL.Path, "/hugo/simplemde.js") {
|
||||||
w.Write(assets.MustAsset("simplemde/debug/simplemde.js"))
|
w.Write(assets.MustAsset("simplemde/debug/simplemde.js"))
|
||||||
return http.StatusOK, nil
|
return nil
|
||||||
}
|
}
|
||||||
if strings.HasPrefix(r.URL.Path, "/hugo/vue.js") {
|
if strings.HasPrefix(r.URL.Path, "/hugo/vue.js") {
|
||||||
w.Write(assets.MustAsset("js/vue.js"))
|
w.Write(assets.MustAsset("js/vue.js"))
|
||||||
return http.StatusOK, nil
|
return nil
|
||||||
}
|
}
|
||||||
if strings.HasPrefix(r.URL.Path, "/hugo/moment.js") {
|
if strings.HasPrefix(r.URL.Path, "/hugo/moment.js") {
|
||||||
w.Write(assets.MustAsset("js/moment.js"))
|
w.Write(assets.MustAsset("js/moment.js"))
|
||||||
return http.StatusOK, nil
|
return nil
|
||||||
}
|
}
|
||||||
if strings.HasPrefix(r.URL.Path, "/hugo/font-awesome.css") {
|
if strings.HasPrefix(r.URL.Path, "/hugo/font-awesome.css") {
|
||||||
w.Write(assets.MustAsset("css/font-awesome.min.css"))
|
w.Write(assets.MustAsset("css/font-awesome.min.css"))
|
||||||
return http.StatusOK, nil
|
return nil
|
||||||
}
|
}
|
||||||
if strings.HasPrefix(r.URL.Path, "/hugo/admin") {
|
if strings.HasPrefix(r.URL.Path, "/hugo/admin") {
|
||||||
return ch.Admin().ServeHTTP(w, r)
|
return ch.Admin().ServeHTTP(w, r)
|
||||||
@@ -73,7 +73,7 @@ func (ch *CaddyHugo) ServeHTTPWithNext(next httpserver.Handler, c *caddy.Control
|
|||||||
return ch.AuthorHome().ServeHTTP(w, r)
|
return ch.AuthorHome().ServeHTTP(w, r)
|
||||||
}
|
}
|
||||||
if strings.HasPrefix(r.URL.Path, "/hugo/edit/") {
|
if strings.HasPrefix(r.URL.Path, "/hugo/edit/") {
|
||||||
return ch.Edit(c).ServeHTTP(w, r)
|
return ch.Edit().ServeHTTP(w, r)
|
||||||
}
|
}
|
||||||
if strings.HasPrefix(r.URL.Path, "/hugo/draft/") {
|
if strings.HasPrefix(r.URL.Path, "/hugo/draft/") {
|
||||||
return ch.serveDraft(w, r)
|
return ch.serveDraft(w, r)
|
||||||
@@ -87,31 +87,27 @@ func (ch *CaddyHugo) ServeHTTPWithNext(next httpserver.Handler, c *caddy.Control
|
|||||||
if strings.HasPrefix(r.URL.Path, "/media/") {
|
if strings.HasPrefix(r.URL.Path, "/media/") {
|
||||||
return ch.serveMedia(w, r)
|
return ch.serveMedia(w, r)
|
||||||
}
|
}
|
||||||
|
if strings.HasPrefix(r.URL.Path, "/hugo/fs/") {
|
||||||
|
printTree(afero.NewOsFs(), w, ch.Dir)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
http.NotFound(w, r)
|
return next.ServeHTTP(w, r)
|
||||||
return 404, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ch *CaddyHugo) ServeNewContent(w http.ResponseWriter, r *http.Request) (int, error) {
|
func (ch *CaddyHugo) ServeNewContent(w http.ResponseWriter, r *http.Request) error {
|
||||||
name := r.FormValue("name")
|
name := r.FormValue("name")
|
||||||
ctype := r.FormValue("type")
|
ctype := r.FormValue("type")
|
||||||
|
|
||||||
filename, err := ch.NewContent(name, ctype)
|
filename, err := ch.NewContent(name, ctype)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println("error creating new content:", err)
|
fmt.Println("error creating new content:", err)
|
||||||
return http.StatusInternalServerError, err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// serve redirect
|
// serve redirect
|
||||||
http.Redirect(w, r, filepath.Join("/hugo/edit/", "content", filename), http.StatusFound)
|
http.Redirect(w, r, filepath.Join("/hugo/edit/", "content", filename), http.StatusFound)
|
||||||
return http.StatusFound, nil
|
return nil
|
||||||
}
|
|
||||||
func (ch *CaddyHugo) Middleware(c *caddy.Controller) httpserver.Middleware {
|
|
||||||
return func(next httpserver.Handler) httpserver.Handler {
|
|
||||||
return httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
|
|
||||||
return ch.ServeHTTPWithNext(next, c, w, r)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ch *CaddyHugo) Auth(r *http.Request) bool {
|
func (ch *CaddyHugo) Auth(r *http.Request) bool {
|
||||||
@@ -139,34 +135,34 @@ func (ch *CaddyHugo) Match(r *http.Request) bool {
|
|||||||
return strings.HasPrefix(r.URL.Path, "/hugo/")
|
return strings.HasPrefix(r.URL.Path, "/hugo/")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ch *CaddyHugo) Admin() httpserver.Handler {
|
func (ch *CaddyHugo) Admin() caddyhttp.Handler {
|
||||||
return httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
|
return caddyhttp.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
|
||||||
err := ch.adminTmpl.Execute(w, ch.TmplData(r, nil))
|
err := ch.adminTmpl.Execute(w, ch.TmplData(r, nil))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
return http.StatusInternalServerError, err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return http.StatusOK, nil
|
return nil
|
||||||
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ch *CaddyHugo) AuthorHome() httpserver.Handler {
|
func (ch *CaddyHugo) AuthorHome() caddyhttp.Handler {
|
||||||
return httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
|
return caddyhttp.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
|
||||||
td := ch.TmplData(r, nil)
|
td := ch.TmplData(r, nil)
|
||||||
err := ch.authorTmpl.Execute(w, td)
|
err := ch.authorTmpl.Execute(w, td)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
return http.StatusInternalServerError, err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return http.StatusOK, nil
|
return nil
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ch *CaddyHugo) Edit(c *caddy.Controller) httpserver.Handler {
|
func (ch *CaddyHugo) Edit() caddyhttp.Handler {
|
||||||
return httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
|
return caddyhttp.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
|
||||||
if r.URL.Path == "/hugo/edit/new" {
|
if r.URL.Path == "/hugo/edit/new" {
|
||||||
return ch.ServeNewContent(w, r)
|
return ch.ServeNewContent(w, r)
|
||||||
}
|
}
|
||||||
@@ -178,32 +174,31 @@ func (ch *CaddyHugo) Edit(c *caddy.Controller) httpserver.Handler {
|
|||||||
doc, err := ch.editSession(docNameFromEditRequest(r))
|
doc, err := ch.editSession(docNameFromEditRequest(r))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
return http.StatusNotFound, err
|
http.Error(w, err.Error(), http.StatusNotFound)
|
||||||
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
err = ch.editTmpl.Execute(w, ch.TmplData(r, doc))
|
err = ch.editTmpl.Execute(w, ch.TmplData(r, doc))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
return http.StatusInternalServerError, err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return http.StatusOK, nil
|
return nil
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ch *CaddyHugo) serveDraft(w http.ResponseWriter, r *http.Request) (int, error) {
|
func (ch *CaddyHugo) serveDraft(w http.ResponseWriter, r *http.Request) error {
|
||||||
pathSegments := strings.SplitN(r.URL.Path, "/", 5)
|
pathSegments := strings.SplitN(r.URL.Path, "/", 5)
|
||||||
if len(pathSegments) < 4 {
|
if len(pathSegments) < 4 {
|
||||||
|
return errors.New("not found")
|
||||||
return http.StatusNotFound, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
encoded := pathSegments[3]
|
encoded := pathSegments[3]
|
||||||
|
|
||||||
nameBytes, err := base64.RawURLEncoding.DecodeString(encoded)
|
nameBytes, err := base64.RawURLEncoding.DecodeString(encoded)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return http.StatusNotFound, err
|
return errors.New("not found")
|
||||||
}
|
}
|
||||||
|
|
||||||
name := string(nameBytes)
|
name := string(nameBytes)
|
||||||
@@ -213,7 +208,7 @@ func (ch *CaddyHugo) serveDraft(w http.ResponseWriter, r *http.Request) (int, er
|
|||||||
|
|
||||||
docref, ok := ch.docs[ch.docFilename(name)]
|
docref, ok := ch.docs[ch.docFilename(name)]
|
||||||
if !ok {
|
if !ok {
|
||||||
return http.StatusNotFound, fmt.Errorf("draft not found")
|
return fmt.Errorf("draft not found")
|
||||||
}
|
}
|
||||||
|
|
||||||
r.URL.Path = strings.ToLower(r.URL.Path)
|
r.URL.Path = strings.ToLower(r.URL.Path)
|
||||||
@@ -224,13 +219,77 @@ func (ch *CaddyHugo) serveDraft(w http.ResponseWriter, r *http.Request) (int, er
|
|||||||
page := ch.HugoSites.GetContentPage(ch.docFilename(name))
|
page := ch.HugoSites.GetContentPage(ch.docFilename(name))
|
||||||
if page == nil {
|
if page == nil {
|
||||||
fmt.Fprintf(w, "can't find %q to display a draft", name)
|
fmt.Fprintf(w, "can't find %q to display a draft", name)
|
||||||
return 404, nil
|
return fmt.Errorf("draft not found")
|
||||||
}
|
}
|
||||||
|
|
||||||
r.URL.Path = page.RelPermalink()
|
r.URL.Path = page.RelPermalink()
|
||||||
http.FileServer(aferoHTTP{afero.NewBasePathFs(docref.tmpfs, path.Join(ch.Dir, "public"))}).ServeHTTP(w, r)
|
http.FileServer(aferoHTTP{afero.NewBasePathFs(docref.tmpfs, path.Join(ch.Dir, "public"))}).ServeHTTP(w, r)
|
||||||
|
|
||||||
return 200, nil
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func printTree(fs afero.Fs, w io.Writer, dir string) {
|
||||||
|
const (
|
||||||
|
Line = " │ "
|
||||||
|
Tab = " "
|
||||||
|
Elbow = " └─"
|
||||||
|
Tee = " ├─"
|
||||||
|
)
|
||||||
|
|
||||||
|
wd, _ := os.Getwd()
|
||||||
|
fmt.Fprintln(w, wd)
|
||||||
|
|
||||||
|
if dir == "" {
|
||||||
|
dir = "/"
|
||||||
|
}
|
||||||
|
|
||||||
|
openDirs := map[string]bool{}
|
||||||
|
lastFiles := map[string]string{}
|
||||||
|
|
||||||
|
afero.Walk(fs, dir, filepath.WalkFunc(func(p string, info os.FileInfo, err error) error {
|
||||||
|
if strings.HasPrefix(p, "./") {
|
||||||
|
p = p[2:]
|
||||||
|
}
|
||||||
|
|
||||||
|
openDirs[filepath.Dir(p)] = true
|
||||||
|
lastFiles[filepath.Dir(p)] = filepath.Base(p)
|
||||||
|
return nil
|
||||||
|
}))
|
||||||
|
|
||||||
|
afero.Walk(fs, dir, filepath.WalkFunc(func(p string, info os.FileInfo, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.HasPrefix(p, "./") {
|
||||||
|
p = p[2:]
|
||||||
|
}
|
||||||
|
|
||||||
|
if filepath.Base(p)[0] == '.' && info.IsDir() {
|
||||||
|
return filepath.SkipDir
|
||||||
|
}
|
||||||
|
|
||||||
|
entry := Tee
|
||||||
|
|
||||||
|
if lastFiles[filepath.Dir(p)] == filepath.Base(p) {
|
||||||
|
openDirs[filepath.Dir(p)] = false
|
||||||
|
entry = Elbow
|
||||||
|
}
|
||||||
|
|
||||||
|
indent := ""
|
||||||
|
dirs := strings.Split(p, string(filepath.Separator))
|
||||||
|
dirs = dirs[:len(dirs)-1]
|
||||||
|
for i := range dirs {
|
||||||
|
if openDirs[filepath.Join(dirs[:i]...)] {
|
||||||
|
indent += Line
|
||||||
|
} else {
|
||||||
|
indent += Tab
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Fprintf(w, "%s%s %s (%s)\n", indent, entry, filepath.Base(p), p)
|
||||||
|
return nil
|
||||||
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
type aferoHTTP struct {
|
type aferoHTTP struct {
|
||||||
@@ -248,9 +307,9 @@ func (a aferoHTTP) Open(name string) (http.File, error) {
|
|||||||
return af, err
|
return af, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ch *CaddyHugo) commentsLogin(r *http.Request, w http.ResponseWriter) (int, error) {
|
func (ch *CaddyHugo) commentsLogin(r *http.Request, w http.ResponseWriter) error {
|
||||||
if ch.Comments == nil {
|
if ch.Comments == nil {
|
||||||
return 200, nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
_, ok := ch.Comments.User(r)
|
_, ok := ch.Comments.User(r)
|
||||||
@@ -258,10 +317,10 @@ func (ch *CaddyHugo) commentsLogin(r *http.Request, w http.ResponseWriter) (int,
|
|||||||
w.Header().Set("WWW-Authenticate", `Basic realm="Log in with your name and the password. Ask Dan or Stephen for the password."`)
|
w.Header().Set("WWW-Authenticate", `Basic realm="Log in with your name and the password. Ask Dan or Stephen for the password."`)
|
||||||
w.WriteHeader(401)
|
w.WriteHeader(401)
|
||||||
fmt.Fprintf(w, "<html><body>Log in with your name and the password. Ask Dan or Stephen for the password. <a href=%q>go back</a></body></html>", r.Referer())
|
fmt.Fprintf(w, "<html><body>Log in with your name and the password. Ask Dan or Stephen for the password. <a href=%q>go back</a></body></html>", r.Referer())
|
||||||
return 200, nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
http.Redirect(w, r, r.Referer(), http.StatusFound)
|
http.Redirect(w, r, r.Referer(), http.StatusFound)
|
||||||
|
|
||||||
return 200, nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,14 +2,18 @@ package caddyhugo
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"os"
|
||||||
"path"
|
"path"
|
||||||
|
"path/filepath"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gohugoio/hugo/deps"
|
"github.com/gohugoio/hugo/deps"
|
||||||
"github.com/gohugoio/hugo/hugofs"
|
"github.com/gohugoio/hugo/hugofs"
|
||||||
"github.com/gohugoio/hugo/hugolib"
|
"github.com/gohugoio/hugo/hugolib"
|
||||||
"github.com/spf13/afero"
|
"github.com/spf13/afero"
|
||||||
|
"github.com/spf13/viper"
|
||||||
|
|
||||||
|
themeadditions "git.stephensearles.com/stephen/caddy-hugo2/theme-additions"
|
||||||
"git.stephensearles.com/stephen/idleshut"
|
"git.stephensearles.com/stephen/idleshut"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -18,37 +22,88 @@ const (
|
|||||||
WebsocketFileTicker = 1 * time.Second
|
WebsocketFileTicker = 1 * time.Second
|
||||||
)
|
)
|
||||||
|
|
||||||
type HugoInteractor interface {
|
// Publish really renders new content into the public directory
|
||||||
Render(srcdir, workdir string) HugoRenderer
|
func (ch *CaddyHugo) Publish() error {
|
||||||
|
err := ch.persistAllEdits()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = buildSite(ch.HugoSites)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type HugoRenderer interface {
|
func buildSite(sites *hugolib.HugoSites) error {
|
||||||
WriteContent(contents string) error
|
err := sites.Build(hugolib.BuildCfg{ResetState: true})
|
||||||
Start() error
|
if err != nil {
|
||||||
Stop() error
|
return fmt.Errorf("caddy-hugo: building site: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeThemeFiles(dir string) error {
|
||||||
|
for _, asset := range themeadditions.AssetNames() {
|
||||||
|
err := os.MkdirAll(path.Join(dir, filepath.Dir(asset)), 0755)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
f, err := os.Create(path.Join(dir, asset))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
b, err := themeadditions.Asset(asset)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = f.Write(b)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = f.Close()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ch *CaddyHugo) configWithFs(fs afero.Fs) (*hugolib.HugoSites, *deps.DepsCfg, error) {
|
||||||
|
var err error
|
||||||
|
|
||||||
|
hfs := hugofs.NewFrom(fs, &viper.Viper{})
|
||||||
|
cfg := &deps.DepsCfg{Fs: hfs}
|
||||||
|
|
||||||
|
cfgPath := path.Join(ch.Dir, "config.toml")
|
||||||
|
cfg.Cfg, _, err = hugolib.LoadConfig(hugolib.ConfigSourceDescriptor{Fs: fs, Path: cfgPath})
|
||||||
|
if err != nil {
|
||||||
|
return nil, cfg, fmt.Errorf("caddy-hugo: loading site configuration: %v", err)
|
||||||
|
}
|
||||||
|
cfg.Cfg.Set("workingDir", ch.Dir)
|
||||||
|
|
||||||
|
sites, err := hugolib.NewHugoSites(*cfg)
|
||||||
|
if err != nil {
|
||||||
|
return nil, cfg, fmt.Errorf("caddy-hugo: initializing site: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = buildSite(sites)
|
||||||
|
|
||||||
|
return sites, cfg, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func HugoInternalProcessConfig(ch *CaddyHugo, es *editSession, touchFn func()) (idleshut.Config, error) {
|
func HugoInternalProcessConfig(ch *CaddyHugo, es *editSession, touchFn func()) (idleshut.Config, error) {
|
||||||
|
hugoSites, _, err := ch.configWithFs(es.tmpfs)
|
||||||
var err error
|
|
||||||
hugoCfg := &deps.DepsCfg{Fs: hugofs.NewFrom(es.tmpfs, ch.HugoCfg.Cfg)}
|
|
||||||
fmt.Println(ch.Dir)
|
|
||||||
hugoCfg.Cfg, err = hugolib.LoadConfig(es.tmpfs, "", path.Join(ch.Dir, "config.toml"))
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return idleshut.Config{}, fmt.Errorf("caddy-hugo: loading site configuration: %v", err)
|
return idleshut.Config{}, fmt.Errorf("caddy-hugo: loading site configuration: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
hugoCfg.Cfg.Set("workingDir", ch.Dir)
|
|
||||||
hugoSites, err := hugolib.NewHugoSites(*hugoCfg)
|
|
||||||
if err != nil {
|
|
||||||
return idleshut.Config{}, fmt.Errorf("caddy-hugo: initializing site: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = hugoSites.Build(hugolib.BuildCfg{ResetState: true})
|
|
||||||
if err != nil {
|
|
||||||
return idleshut.Config{}, fmt.Errorf("caddy-hugo: building site: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return idleshut.Config{
|
return idleshut.Config{
|
||||||
TickDuration: WebsocketFileTicker,
|
TickDuration: WebsocketFileTicker,
|
||||||
MaxIdleTicks: uint(IdleWebsocketTimeout/WebsocketFileTicker) + 1,
|
MaxIdleTicks: uint(IdleWebsocketTimeout/WebsocketFileTicker) + 1,
|
||||||
@@ -72,7 +127,7 @@ func HugoInternalProcessConfig(ch *CaddyHugo, es *editSession, touchFn func()) (
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
err = hugoSites.Build(hugolib.BuildCfg{ResetState: true})
|
err = buildSite(hugoSites)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
.PHONY: run
|
||||||
|
run: CADDY_DEBUG=1
|
||||||
|
run:
|
||||||
|
xcaddy build --with git.stephensearles.com/stephen/caddy-hugo2@latest=./ && cd testdir && ../caddy run --config Caddyfile
|
||||||
|
|
||||||
|
.PHONY: build
|
||||||
|
build:
|
||||||
|
xcaddy build --with github.com/caddy-dns/digitalocean --with git.stephensearles.com/stephen/caddy-hugo2@latest=./
|
||||||
@@ -1,218 +1,63 @@
|
|||||||
package caddyhugo
|
package caddyhugo
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"fmt"
|
"fmt"
|
||||||
"image"
|
|
||||||
_ "image/gif" // for processing images
|
|
||||||
"image/jpeg"
|
|
||||||
_ "image/png" // for processing images
|
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"net/url"
|
||||||
"path"
|
"path"
|
||||||
"path/filepath"
|
|
||||||
"regexp"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/nfnt/resize"
|
"github.com/PuerkitoBio/goquery"
|
||||||
|
"github.com/gohugoio/hugo/resources/page"
|
||||||
|
|
||||||
|
"git.stephensearles.com/stephen/caddy-hugo2/media"
|
||||||
)
|
)
|
||||||
|
|
||||||
type MediaSource struct {
|
func (ch *CaddyHugo) ReferencedMedia() map[string]map[page.Page]struct{} {
|
||||||
StorageDir string
|
found := map[string]map[page.Page]struct{}{}
|
||||||
ThumbDir string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ms *MediaSource) LocationOrig(m Media) string {
|
for _, pg := range ch.HugoSites.Pages() {
|
||||||
return path.Join(ms.StorageDir, m.Name)
|
renderOutput, err := pg.Render()
|
||||||
}
|
|
||||||
|
|
||||||
func (ms *MediaSource) ThumbPath(m Media, size image.Rectangle) string {
|
|
||||||
w := size.Dx()
|
|
||||||
h := size.Dy()
|
|
||||||
|
|
||||||
var ws, hs string
|
|
||||||
|
|
||||||
if w != 0 {
|
|
||||||
ws = fmt.Sprint(w)
|
|
||||||
}
|
|
||||||
if h != 0 {
|
|
||||||
hs = fmt.Sprint(h)
|
|
||||||
}
|
|
||||||
|
|
||||||
thumbSlug := filepath.Join(fmt.Sprintf("%sx%s", ws, hs), m.Name)
|
|
||||||
return path.Join("/media", thumbSlug)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ms *MediaSource) ThumbFilename(m Media, size image.Rectangle) string {
|
|
||||||
return filepath.Join(ms.ThumbDir, ms.ThumbPath(m, size))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ms *MediaSource) receiveNewMedia(name string, r io.Reader) error {
|
|
||||||
dest := path.Join(ms.StorageDir, name)
|
|
||||||
f, err := os.OpenFile(dest, os.O_WRONLY|os.O_CREATE, 0644)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = io.Copy(f, r)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
return f.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
type Media struct {
|
|
||||||
Type string
|
|
||||||
Name string
|
|
||||||
Size image.Rectangle
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ms *MediaSource) Size(name string) (image.Rectangle, error) {
|
|
||||||
f, err := os.Open(name)
|
|
||||||
if err != nil {
|
|
||||||
return image.ZR, err
|
|
||||||
}
|
|
||||||
defer f.Close()
|
|
||||||
|
|
||||||
cfg, _, err := image.DecodeConfig(f)
|
|
||||||
if err != nil {
|
|
||||||
return image.ZR, err
|
|
||||||
}
|
|
||||||
|
|
||||||
width := cfg.Width
|
|
||||||
height := cfg.Height
|
|
||||||
|
|
||||||
return image.Rect(0, 0, width, height), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ms *MediaSource) ThumbMax(m Media, maxDim int) (string, image.Rectangle, error) {
|
|
||||||
f, err := os.Open(ms.LocationOrig(m))
|
|
||||||
if err != nil {
|
|
||||||
return "", image.ZR, err
|
|
||||||
}
|
|
||||||
defer f.Close()
|
|
||||||
|
|
||||||
cfg, _, err := image.DecodeConfig(f)
|
|
||||||
if err != nil {
|
|
||||||
return "", image.ZR, err
|
|
||||||
}
|
|
||||||
|
|
||||||
width := cfg.Width
|
|
||||||
height := cfg.Height
|
|
||||||
|
|
||||||
if width > height {
|
|
||||||
height = height * maxDim / width
|
|
||||||
width = maxDim
|
|
||||||
} else {
|
|
||||||
width = width * maxDim / height
|
|
||||||
height = maxDim
|
|
||||||
}
|
|
||||||
|
|
||||||
size := image.Rect(0, 0, width, height)
|
|
||||||
if ms.HasThumb(m, size) {
|
|
||||||
return ms.ThumbPath(m, size), size, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = f.Seek(0, io.SeekStart)
|
|
||||||
if err != nil {
|
|
||||||
return "", image.ZR, err
|
|
||||||
}
|
|
||||||
|
|
||||||
img, _, err := image.Decode(f)
|
|
||||||
if err != nil {
|
|
||||||
return "", image.ZR, err
|
|
||||||
}
|
|
||||||
|
|
||||||
src, err := ms.ThumbImage(img, m, size)
|
|
||||||
return src, size, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ms *MediaSource) HasThumb(m Media, size image.Rectangle) bool {
|
|
||||||
_, err := os.Stat(ms.ThumbFilename(m, size))
|
|
||||||
return err == nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ms *MediaSource) ByName(name string) *Media {
|
|
||||||
size, _ := ms.Size(path.Join(ms.StorageDir, name))
|
|
||||||
return &Media{
|
|
||||||
Type: "image",
|
|
||||||
Name: name,
|
|
||||||
Size: size,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ms *MediaSource) Thumb(m Media, size image.Rectangle) (string, error) {
|
|
||||||
if ms.HasThumb(m, size) {
|
|
||||||
return ms.ThumbPath(m, size), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
f, err := os.Open(ms.LocationOrig(m))
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
defer f.Close()
|
|
||||||
|
|
||||||
img, _, err := image.Decode(f)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
return ms.ThumbImage(img, m, size)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ms *MediaSource) ThumbImage(img image.Image, m Media, size image.Rectangle) (string, error) {
|
|
||||||
|
|
||||||
thumbLoc := ms.ThumbFilename(m, size)
|
|
||||||
os.MkdirAll(path.Dir(thumbLoc), 0755)
|
|
||||||
fthumb, err := os.OpenFile(thumbLoc, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0655)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
img = resize.Resize(uint(size.Dx()), uint(size.Dy()), img, resize.Bilinear)
|
|
||||||
|
|
||||||
err = jpeg.Encode(fthumb, img, nil)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
err = fthumb.Close()
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
return ms.ThumbPath(m, size), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ms *MediaSource) Walk() ([]*Media, error) {
|
|
||||||
var media []*Media
|
|
||||||
|
|
||||||
err := filepath.Walk(ms.StorageDir, func(name string, fi os.FileInfo, err error) error {
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
continue
|
||||||
}
|
}
|
||||||
if fi.IsDir() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
media = append(media, ms.ByName(path.Base(name)))
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
|
|
||||||
return media, err
|
r := bytes.NewBufferString(string(renderOutput))
|
||||||
|
doc, err := goquery.NewDocumentFromReader(r)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
doc.Find("img,video").Map(func(i int, s *goquery.Selection) string {
|
||||||
|
u, ok := s.Attr("src")
|
||||||
|
if ok {
|
||||||
|
u = path.Base(u)
|
||||||
|
if ud, err := url.QueryUnescape(u); err == nil {
|
||||||
|
u = ud
|
||||||
|
}
|
||||||
|
if m := found[u]; m == nil {
|
||||||
|
found[u] = make(map[page.Page]struct{})
|
||||||
|
}
|
||||||
|
found[u][pg] = struct{}{}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
})
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
return found
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ch *CaddyHugo) uploadMedia(w http.ResponseWriter, r *http.Request) (int, error) {
|
func (ch *CaddyHugo) uploadMedia(w http.ResponseWriter, r *http.Request) error {
|
||||||
if ch.Media == nil {
|
if ch.Media == nil {
|
||||||
http.NotFound(w, r)
|
http.NotFound(w, r)
|
||||||
return 404, nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
mr, err := r.MultipartReader()
|
mr, err := r.MultipartReader()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
return 400, nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
for {
|
for {
|
||||||
@@ -222,28 +67,30 @@ func (ch *CaddyHugo) uploadMedia(w http.ResponseWriter, r *http.Request) (int, e
|
|||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
return 400, nil
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
name := part.FileName()
|
name := part.FileName()
|
||||||
if name != "" {
|
if name != "" {
|
||||||
err = ch.Media.receiveNewMedia(name, part)
|
err = ch.Media.ReceiveNewMedia(name, part)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
return 500, nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return 200, nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ch *CaddyHugo) serveMediaPage(w http.ResponseWriter, r *http.Request) (int, error) {
|
func (ch *CaddyHugo) serveMediaPage(w http.ResponseWriter, r *http.Request) error {
|
||||||
if ch.Media == nil {
|
if ch.Media == nil {
|
||||||
http.NotFound(w, r)
|
http.NotFound(w, r)
|
||||||
return 404, nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
referenced := ch.ReferencedMedia()
|
||||||
|
|
||||||
io.WriteString(w, `<html>
|
io.WriteString(w, `<html>
|
||||||
<head><style>
|
<head><style>
|
||||||
iframe { height: 100%; }
|
iframe { height: 100%; }
|
||||||
@@ -269,20 +116,34 @@ func (ch *CaddyHugo) serveMediaPage(w http.ResponseWriter, r *http.Request) (int
|
|||||||
<div style="display: inline-block; width: 100%; height: 10vh;"></div>
|
<div style="display: inline-block; width: 100%; height: 10vh;"></div>
|
||||||
`)
|
`)
|
||||||
if ch.Media != nil {
|
if ch.Media != nil {
|
||||||
media, err := ch.Media.Walk()
|
mm, err := ch.Media.Walk()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
return 500, nil
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, m := range media {
|
for _, m := range media.Set(mm).ByDate() {
|
||||||
|
|
||||||
src, size, err := ch.Media.ThumbMax(*m, 100)
|
size, err := ch.Media.ThumbMax(*m, 100)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(w, `<div class="img">error rendering %q: %v</div>`, m.Name, err)
|
fmt.Fprintf(w, `<div class="img">error rendering %q: %v</div>`, m.Name, err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
fmt.Fprintf(w, `<div class="img"><img width=%d height=%d src=%q data-filename=%q /><br /><input type="text" readonly value=%q /><span class="copy">📋</span></div>`, size.Dx(), size.Dy(), src, m.Name, src)
|
|
||||||
|
refs := len(referenced[m.Name])
|
||||||
|
plural := "s"
|
||||||
|
if refs == 1 {
|
||||||
|
plural = ""
|
||||||
|
}
|
||||||
|
refLine := fmt.Sprintf("included on %d page%s", refs, plural)
|
||||||
|
|
||||||
|
switch m.Type {
|
||||||
|
case media.TypeImage:
|
||||||
|
fmt.Fprintf(w, `<div class="img"><img width=%d height=%d src=%q data-filename=%q /><br /><input type="text" readonly value=%q /><span class="copy">📋</span><br />%s</div>`, size.Dx(), size.Dy(), m.ThumbPath(size), m.Name, m.ThumbPath(size), refLine)
|
||||||
|
case media.TypeVideo:
|
||||||
|
// TODO: onmouseover sucks for mobile
|
||||||
|
fmt.Fprintf(w, `<div class="img"><video width=%d height=%d src=%q data-filename=%q onmouseover="this.play()" onmouseout="this.pause();this.currentTime=0;"></video><br /><input type="text" readonly value=%q /><span class="copy">📋</span><br />%s</div>`, size.Dx(), size.Dy(), m.ThumbPath(size), m.Name, m.ThumbPath(size), refLine)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
io.WriteString(w, `<script>
|
io.WriteString(w, `<script>
|
||||||
@@ -294,7 +155,7 @@ func (ch *CaddyHugo) serveMediaPage(w http.ResponseWriter, r *http.Request) (int
|
|||||||
evt.target.previousSibling.select();
|
evt.target.previousSibling.select();
|
||||||
document.execCommand("copy");
|
document.execCommand("copy");
|
||||||
}
|
}
|
||||||
if (evt.target.tagName === "IMG") {
|
if (evt.target.tagName === "IMG" || evt.target.tagName === "VIDEO") {
|
||||||
var current = document.querySelector(".img.selected");
|
var current = document.querySelector(".img.selected");
|
||||||
if (current) {
|
if (current) {
|
||||||
current.classList = "img";
|
current.classList = "img";
|
||||||
@@ -311,92 +172,15 @@ func (ch *CaddyHugo) serveMediaPage(w http.ResponseWriter, r *http.Request) (int
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
</script></body><html>`)
|
</script></body><html>`)
|
||||||
return 200, nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
func (ch *CaddyHugo) serveMedia(w http.ResponseWriter, r *http.Request) error {
|
||||||
sizeString = regexp.MustCompile(`([0-9]*)(x)?([0-9]*)`)
|
|
||||||
)
|
|
||||||
|
|
||||||
func parseSizeString(str string, actual image.Rectangle) (image.Rectangle, error) {
|
|
||||||
var err = fmt.Errorf("expected a size string {width}x{height}, saw %q", str)
|
|
||||||
|
|
||||||
strs := sizeString.FindStringSubmatch(str)
|
|
||||||
if len(strs) < 4 {
|
|
||||||
return image.ZR, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var w, h int
|
|
||||||
var strconvErr error
|
|
||||||
|
|
||||||
if strs[1] != "" {
|
|
||||||
w, strconvErr = strconv.Atoi(strs[1])
|
|
||||||
if strconvErr != nil {
|
|
||||||
return image.ZR, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if strs[3] != "" {
|
|
||||||
h, strconvErr = strconv.Atoi(strs[3])
|
|
||||||
if strconvErr != nil {
|
|
||||||
return image.ZR, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if strs[2] != "x" {
|
|
||||||
// w was the only dimension given, so set it to the greater dimension
|
|
||||||
// of the actual image size
|
|
||||||
if actual.Dx() > actual.Dy() {
|
|
||||||
h = 0
|
|
||||||
} else {
|
|
||||||
h = w
|
|
||||||
w = 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return image.Rect(0, 0, w, h), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *CaddyHugo) serveMedia(w http.ResponseWriter, r *http.Request) (int, error) {
|
|
||||||
if ch.Media == nil {
|
if ch.Media == nil {
|
||||||
http.NotFound(w, r)
|
http.NotFound(w, r)
|
||||||
return 404, nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
segs := strings.Split(r.URL.Path, "/")
|
ch.Media.ServeHTTP(w, r)
|
||||||
name := segs[len(segs)-1] // the last segment is the filename
|
return nil
|
||||||
|
|
||||||
size := image.Rectangle{}
|
|
||||||
|
|
||||||
m := ch.Media.ByName(name)
|
|
||||||
|
|
||||||
if len(segs) >= 4 && len(segs) > 2 {
|
|
||||||
var err error
|
|
||||||
size, err = parseSizeString(segs[len(segs)-2], m.Size)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
||||||
return 400, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
file, err := ch.Media.Thumb(*m, size)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, fmt.Sprintf("unable to load thumb"), http.StatusInternalServerError)
|
|
||||||
return 500, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if file[0] == '/' {
|
|
||||||
file = file[1:]
|
|
||||||
}
|
|
||||||
|
|
||||||
file = path.Join(ch.Media.ThumbDir, file)
|
|
||||||
|
|
||||||
http.ServeFile(w, r, file)
|
|
||||||
|
|
||||||
return 200, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func removeExtension(name string) string {
|
|
||||||
ext := path.Ext(name)
|
|
||||||
return name[:len(name)-len(ext)]
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package media
|
||||||
|
|
||||||
|
import (
|
||||||
|
"image"
|
||||||
|
"image/jpeg"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
|
|
||||||
|
"github.com/nfnt/resize"
|
||||||
|
)
|
||||||
|
|
||||||
|
func imageSize(name string) (image.Rectangle, error) {
|
||||||
|
f, err := os.Open(name)
|
||||||
|
if err != nil {
|
||||||
|
return image.ZR, err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
|
||||||
|
cfg, _, err := image.DecodeConfig(f)
|
||||||
|
if err != nil {
|
||||||
|
return image.ZR, err
|
||||||
|
}
|
||||||
|
|
||||||
|
width := cfg.Width
|
||||||
|
height := cfg.Height
|
||||||
|
|
||||||
|
return image.Rect(0, 0, width, height), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ThumbImage(filename string, img image.Image, size image.Rectangle) error {
|
||||||
|
os.MkdirAll(path.Dir(filename), 0755)
|
||||||
|
fthumb, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0655)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
img = resize.Resize(uint(size.Dx()), uint(size.Dy()), img, resize.Bilinear)
|
||||||
|
|
||||||
|
err = jpeg.Encode(fthumb, img, nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = fthumb.Close()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
+199
@@ -0,0 +1,199 @@
|
|||||||
|
package media
|
||||||
|
|
||||||
|
import (
|
||||||
|
"image"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
|
"path/filepath"
|
||||||
|
"sort"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
// for processing images
|
||||||
|
_ "image/gif"
|
||||||
|
_ "image/png"
|
||||||
|
|
||||||
|
"github.com/tajtiattila/metadata"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
TypeImage = "image"
|
||||||
|
TypeVideo = "video"
|
||||||
|
)
|
||||||
|
|
||||||
|
type MediaSource struct {
|
||||||
|
StorageDir string
|
||||||
|
ThumbDir string
|
||||||
|
|
||||||
|
set Set
|
||||||
|
}
|
||||||
|
|
||||||
|
type Media struct {
|
||||||
|
Type string
|
||||||
|
Name string
|
||||||
|
Size image.Rectangle
|
||||||
|
FullName string
|
||||||
|
|
||||||
|
ms *MediaSource
|
||||||
|
metadata *metadata.Metadata
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m Media) ThumbPath(size image.Rectangle) string {
|
||||||
|
return "/" + thumbPath(size, m.Name)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m Media) ThumbFilename(size image.Rectangle) string {
|
||||||
|
size = m.NormalizeSize(size)
|
||||||
|
return thumbFilename(m.ms.ThumbDir, size, m.Name)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ms *MediaSource) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
|
m, err := ms.ByName(path.Base(r.URL.Path))
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
sizeRequested, err := SizeRequested(r.URL.Path, m.Size)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
size, err := ms.Thumb(*m, sizeRequested)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
http.ServeFile(w, r, m.ThumbFilename(size))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ms *MediaSource) ReceiveNewMedia(name string, r io.Reader) error {
|
||||||
|
ms.set = nil
|
||||||
|
|
||||||
|
dest := path.Join(ms.StorageDir, name)
|
||||||
|
f, err := os.OpenFile(dest, os.O_WRONLY|os.O_CREATE, 0644)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = io.Copy(f, r)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return f.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Media) Date() time.Time {
|
||||||
|
m.getMetadata()
|
||||||
|
|
||||||
|
if m.metadata != nil {
|
||||||
|
raw := m.metadata.Get(metadata.DateTimeOriginal)
|
||||||
|
if raw != "" {
|
||||||
|
d, err := time.Parse("2006-01-02T15:04:05", raw)
|
||||||
|
if err == nil {
|
||||||
|
return d
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fi, err := os.Stat(m.FullName)
|
||||||
|
if err == nil {
|
||||||
|
return fi.ModTime()
|
||||||
|
}
|
||||||
|
|
||||||
|
return time.Time{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Media) getMetadata() error {
|
||||||
|
if m.metadata != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
f, err := os.Open(m.FullName)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
md, err := metadata.Parse(f)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
m.metadata = md
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ms *MediaSource) Size(name string) (image.Rectangle, error) {
|
||||||
|
switch filepath.Ext(name) {
|
||||||
|
case ".mp4":
|
||||||
|
return VideoSize(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
return imageSize(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ms *MediaSource) ByName(name string) (*Media, error) {
|
||||||
|
ext := filepath.Ext(name)
|
||||||
|
typ := TypeImage
|
||||||
|
|
||||||
|
switch ext {
|
||||||
|
case ".mp4":
|
||||||
|
typ = TypeVideo
|
||||||
|
}
|
||||||
|
|
||||||
|
fullName := path.Join(ms.StorageDir, name)
|
||||||
|
size, _ := ms.Size(fullName)
|
||||||
|
|
||||||
|
return &Media{
|
||||||
|
Type: typ,
|
||||||
|
Name: name,
|
||||||
|
Size: size,
|
||||||
|
FullName: fullName,
|
||||||
|
ms: ms,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ms *MediaSource) Walk() ([]*Media, error) {
|
||||||
|
if ms.set == nil {
|
||||||
|
var media []*Media
|
||||||
|
|
||||||
|
err := filepath.Walk(ms.StorageDir, func(name string, fi os.FileInfo, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if fi.IsDir() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
m, err := ms.ByName(path.Base(name))
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
media = append(media, m)
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return media, err
|
||||||
|
}
|
||||||
|
|
||||||
|
ms.set = media
|
||||||
|
}
|
||||||
|
|
||||||
|
return ms.set, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type Set []*Media
|
||||||
|
|
||||||
|
func (s Set) ByDate() Set {
|
||||||
|
sort.Slice(s, func(i, j int) bool {
|
||||||
|
return s[i].Date().After(s[j].Date())
|
||||||
|
})
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
func removeExtension(name string) string {
|
||||||
|
ext := path.Ext(name)
|
||||||
|
return name[:len(name)-len(ext)]
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package caddyhugo
|
package media
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
@@ -33,7 +33,7 @@ func TestThumbSizeStrings(t *testing.T) {
|
|||||||
|
|
||||||
for _, c := range cases {
|
for _, c := range cases {
|
||||||
t.Run(fmt.Sprint(c.input, "=>", c.actualSize), func(t *testing.T) {
|
t.Run(fmt.Sprint(c.input, "=>", c.actualSize), func(t *testing.T) {
|
||||||
got, err := parseSizeString(c.input, image.Rect(0, 0, 100, 100))
|
got, err := ParseSizeString(c.input, image.Rect(0, 0, 100, 100))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Errorf("error parsing size string: %v", err)
|
t.Errorf("error parsing size string: %v", err)
|
||||||
return
|
return
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
package media
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"image"
|
||||||
|
"regexp"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
sizeString = regexp.MustCompile(`([0-9]*)(x)?([0-9]*)`)
|
||||||
|
)
|
||||||
|
|
||||||
|
func SizeRequested(urlpath string, actual image.Rectangle) (image.Rectangle, error) {
|
||||||
|
segments := strings.Count(urlpath, "/")
|
||||||
|
if segments < 3 {
|
||||||
|
return actual, nil
|
||||||
|
}
|
||||||
|
sizeSpec := strings.Split(urlpath, "/")[2]
|
||||||
|
return ParseSizeString(sizeSpec, actual)
|
||||||
|
}
|
||||||
|
|
||||||
|
func ParseSizeString(str string, actual image.Rectangle) (image.Rectangle, error) {
|
||||||
|
var err = fmt.Errorf("expected a size string {width}x{height}, saw %q", str)
|
||||||
|
|
||||||
|
strs := sizeString.FindStringSubmatch(str)
|
||||||
|
if len(strs) < 4 {
|
||||||
|
return image.ZR, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var w, h int
|
||||||
|
var strconvErr error
|
||||||
|
|
||||||
|
if strs[1] != "" {
|
||||||
|
w, strconvErr = strconv.Atoi(strs[1])
|
||||||
|
if strconvErr != nil {
|
||||||
|
return image.ZR, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if strs[3] != "" {
|
||||||
|
h, strconvErr = strconv.Atoi(strs[3])
|
||||||
|
if strconvErr != nil {
|
||||||
|
return image.ZR, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if strs[2] != "x" {
|
||||||
|
// w was the only dimension given, so set it to the greater dimension
|
||||||
|
// of the actual image size
|
||||||
|
if actual.Dx() > actual.Dy() {
|
||||||
|
h = 0
|
||||||
|
} else {
|
||||||
|
h = w
|
||||||
|
w = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return image.Rect(0, 0, w, h), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NormalizeSize(media, requested image.Rectangle) image.Rectangle {
|
||||||
|
if requested.Dx() == 0 && requested.Dy() == 0 {
|
||||||
|
return media
|
||||||
|
}
|
||||||
|
if requested.Dy()%2 == 1 {
|
||||||
|
requested.Max.Y--
|
||||||
|
}
|
||||||
|
if requested.Dx() != 0 && requested.Dy() != 0 {
|
||||||
|
return requested
|
||||||
|
}
|
||||||
|
scaled := image.Rectangle{}
|
||||||
|
if requested.Dx() == 0 {
|
||||||
|
scaled.Max.Y = requested.Dy()
|
||||||
|
scaled.Max.X = requested.Dy() * media.Dx() / media.Dy()
|
||||||
|
}
|
||||||
|
if requested.Dy() == 0 {
|
||||||
|
scaled.Max.X = requested.Dx()
|
||||||
|
scaled.Max.Y = requested.Dx() * media.Dy() / media.Dx()
|
||||||
|
for scaled.Max.Y%2 == 1 {
|
||||||
|
requested.Max.X--
|
||||||
|
scaled.Max.X = requested.Dx()
|
||||||
|
scaled.Max.Y = requested.Dx() * media.Dy() / media.Dx()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return scaled
|
||||||
|
}
|
||||||
+110
@@ -0,0 +1,110 @@
|
|||||||
|
package media
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"image"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
|
"path/filepath"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (ms *MediaSource) ThumbPath(m Media, size image.Rectangle) string {
|
||||||
|
size = m.NormalizeSize(size)
|
||||||
|
return thumbPath(size, m.Name)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ms *MediaSource) ThumbFilename(m Media, size image.Rectangle) string {
|
||||||
|
size = m.NormalizeSize(size)
|
||||||
|
return thumbFilename(ms.ThumbDir, size, m.Name)
|
||||||
|
}
|
||||||
|
|
||||||
|
func thumbFilename(dir string, size image.Rectangle, name string) string {
|
||||||
|
return filepath.Join(dir, thumbPath(size, name))
|
||||||
|
}
|
||||||
|
|
||||||
|
func thumbPath(size image.Rectangle, name string) string {
|
||||||
|
w := size.Dx()
|
||||||
|
h := size.Dy()
|
||||||
|
|
||||||
|
var ws, hs string
|
||||||
|
|
||||||
|
if w != 0 {
|
||||||
|
ws = fmt.Sprint(w)
|
||||||
|
}
|
||||||
|
if h != 0 {
|
||||||
|
hs = fmt.Sprint(h)
|
||||||
|
}
|
||||||
|
|
||||||
|
thumbSlug := filepath.Join(fmt.Sprintf("%sx%s", ws, hs), name)
|
||||||
|
return path.Join("", "media", thumbSlug)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ms *MediaSource) ThumbMax(m Media, maxDim int) (image.Rectangle, error) {
|
||||||
|
width := m.Size.Dx()
|
||||||
|
height := m.Size.Dy()
|
||||||
|
|
||||||
|
if width == 0 && height == 0 {
|
||||||
|
return m.Size, fmt.Errorf("invalid media")
|
||||||
|
}
|
||||||
|
|
||||||
|
if width > height {
|
||||||
|
height = height * maxDim / width
|
||||||
|
width = maxDim
|
||||||
|
} else {
|
||||||
|
width = width * maxDim / height
|
||||||
|
height = maxDim
|
||||||
|
}
|
||||||
|
|
||||||
|
size := image.Rect(0, 0, width, height)
|
||||||
|
actual, err := ms.Thumb(m, size)
|
||||||
|
return actual, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ms *MediaSource) HasThumb(m Media, size image.Rectangle) bool {
|
||||||
|
fi, err := os.Stat(ms.ThumbFilename(m, size))
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return m.Date().Before(fi.ModTime())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m Media) NormalizeSize(size image.Rectangle) image.Rectangle {
|
||||||
|
return NormalizeSize(m.Size, size)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ms *MediaSource) Thumb(m Media, size image.Rectangle) (image.Rectangle, error) {
|
||||||
|
size = m.NormalizeSize(size)
|
||||||
|
|
||||||
|
if ms.HasThumb(m, size) {
|
||||||
|
return size, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
f, err := os.Open(m.FullName)
|
||||||
|
if err != nil {
|
||||||
|
return size, err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
|
||||||
|
return size, ms.thumbReader(f, m, size)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ms *MediaSource) thumbReader(r io.Reader, m Media, size image.Rectangle) error {
|
||||||
|
size = m.NormalizeSize(size)
|
||||||
|
|
||||||
|
switch m.Type {
|
||||||
|
case TypeImage:
|
||||||
|
img, _, err := image.Decode(r)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
filename := ms.ThumbFilename(m, size)
|
||||||
|
return ThumbImage(filename, img, size)
|
||||||
|
case TypeVideo:
|
||||||
|
return VideoEncode(m.FullName, size, ms.ThumbDir)
|
||||||
|
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("cannot thumb media type %q", m.Type)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package media
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"image"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path"
|
||||||
|
"path/filepath"
|
||||||
|
)
|
||||||
|
|
||||||
|
func VideoFrame(filename string) (image.Image, error) {
|
||||||
|
cmd := exec.Command("ffmpeg", "-i", filename, "-vframes", "1", "-f", "singlejpeg", "-")
|
||||||
|
buffer := new(bytes.Buffer)
|
||||||
|
cmd.Stdout = buffer
|
||||||
|
if cmd.Run() != nil {
|
||||||
|
return nil, fmt.Errorf("could not generate frame")
|
||||||
|
}
|
||||||
|
|
||||||
|
img, _, err := image.Decode(buffer)
|
||||||
|
return img, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func VideoSize(filename string) (image.Rectangle, error) {
|
||||||
|
img, err := VideoFrame(filename)
|
||||||
|
if err != nil {
|
||||||
|
return image.Rectangle{}, err
|
||||||
|
}
|
||||||
|
return img.Bounds(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func VideoEncode(filename string, size image.Rectangle, thumbDir string) error {
|
||||||
|
dest := thumbFilename(thumbDir, size, path.Base(filename))
|
||||||
|
os.MkdirAll(filepath.Dir(dest), 0755)
|
||||||
|
cmd := exec.Command("ffmpeg", "-i", filename, "-vf", fmt.Sprintf("scale=%d:%d", size.Dx(), size.Dy()), "-strict", "-2", dest)
|
||||||
|
if out, err := cmd.CombinedOutput(); err != nil {
|
||||||
|
os.Remove(dest)
|
||||||
|
return fmt.Errorf("could not thumb video: %s", string(out))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -3,28 +3,30 @@ package caddyhugo
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"html/template"
|
"html/template"
|
||||||
"io/ioutil"
|
|
||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
|
|
||||||
"git.stephensearles.com/stephen/caddy-hugo2/comments"
|
"git.stephensearles.com/stephen/caddy-hugo2/comments"
|
||||||
|
"git.stephensearles.com/stephen/caddy-hugo2/media"
|
||||||
|
|
||||||
"github.com/gohugoio/hugo/deps"
|
|
||||||
"github.com/gohugoio/hugo/hugofs"
|
"github.com/gohugoio/hugo/hugofs"
|
||||||
"github.com/gohugoio/hugo/hugolib"
|
|
||||||
"github.com/mholt/caddy"
|
|
||||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func (ch *CaddyHugo) SetupCaddy(c *caddy.Controller) error {
|
var eventHookCounter uint64
|
||||||
ch.Site = httpserver.GetConfig(c)
|
|
||||||
err := ch.Setup(ch.Site.Root)
|
|
||||||
|
|
||||||
caddy.RegisterEventHook("caddyhugo-shutdown", func(eventType caddy.EventName, eventInfo interface{}) error {
|
/*
|
||||||
if eventType == caddy.ShutdownEvent {
|
func SetupCaddy(c *caddy.Controller) error {
|
||||||
return ch.persistAllEdits()
|
ch := &CaddyHugo{}
|
||||||
}
|
|
||||||
return nil
|
ch.Site = httpserver.GetConfig(c)
|
||||||
|
root, err := filepath.Abs(ch.Site.Root)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
err = ch.Setup(root)
|
||||||
|
|
||||||
|
c.OnShutdown(func() error {
|
||||||
|
return ch.persistAllEdits()
|
||||||
})
|
})
|
||||||
|
|
||||||
ch.Site.AddMiddleware(ch.Middleware(c))
|
ch.Site.AddMiddleware(ch.Middleware(c))
|
||||||
@@ -32,18 +34,13 @@ func (ch *CaddyHugo) SetupCaddy(c *caddy.Controller) error {
|
|||||||
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
func (ch *CaddyHugo) commentsSetting(c *caddy.Controller) {
|
func (ch *CaddyHugo) commentsSetting() {
|
||||||
for c.NextLine() {
|
if ch.Site.CommentsEnabled {
|
||||||
if c.Val() == "hugo" {
|
ch.Comments = comments.WithStorage(comments.NewDiskv(path.Join(ch.Site.Root, "comments")))
|
||||||
for c.NextBlock() {
|
if ch.Site.CommentsPassword != "" {
|
||||||
if c.Val() == "comments" {
|
ch.Comments.Password = ch.Site.CommentsPassword
|
||||||
ch.Comments = comments.WithStorage(comments.NewDiskv(path.Join(ch.Site.Root, "comments")))
|
|
||||||
if c.NextArg() {
|
|
||||||
ch.Comments.Password = c.Val()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -51,21 +48,14 @@ func (ch *CaddyHugo) commentsSetting(c *caddy.Controller) {
|
|||||||
func (ch *CaddyHugo) Setup(dir string) error {
|
func (ch *CaddyHugo) Setup(dir string) error {
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
|
ch.log("setting up caddy-hugo in", dir)
|
||||||
ch.Dir = dir
|
ch.Dir = dir
|
||||||
ch.docs = make(map[string]*editSession)
|
ch.docs = make(map[string]*editSession)
|
||||||
ch.confirmingToClient = make(map[uint64]struct{})
|
ch.confirmingToClient = make(map[uint64]struct{})
|
||||||
|
|
||||||
ch.HugoCfg = &deps.DepsCfg{}
|
ch.HugoSites, ch.HugoCfg, err = ch.configWithFs(hugofs.Os)
|
||||||
|
|
||||||
ch.HugoCfg.Cfg, err = hugolib.LoadConfig(hugofs.Os, dir, "")
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("error loading hugo config: %v", err)
|
return fmt.Errorf("error setting up hugo : %v", err)
|
||||||
}
|
|
||||||
|
|
||||||
ch.HugoCfg.Cfg.Set("workingdir", dir)
|
|
||||||
ch.HugoSites, err = hugolib.NewHugoSites(*ch.HugoCfg)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("error intializing hugo: %v", err)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
err = ch.Build()
|
err = ch.Build()
|
||||||
@@ -88,14 +78,9 @@ func (ch *CaddyHugo) Setup(dir string) error {
|
|||||||
return fmt.Errorf("edit template invalid: %v", err)
|
return fmt.Errorf("edit template invalid: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
thumbDir, err := ioutil.TempDir("", "thumbs")
|
ch.Media = &media.MediaSource{
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("couldn't initialize media: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
ch.Media = &MediaSource{
|
|
||||||
StorageDir: path.Join(dir, "media"),
|
StorageDir: path.Join(dir, "media"),
|
||||||
ThumbDir: thumbDir,
|
ThumbDir: path.Join(dir, "thumbs"),
|
||||||
}
|
}
|
||||||
|
|
||||||
err = os.MkdirAll(ch.Media.StorageDir, 0755)
|
err = os.MkdirAll(ch.Media.StorageDir, 0755)
|
||||||
@@ -103,6 +88,11 @@ func (ch *CaddyHugo) Setup(dir string) error {
|
|||||||
return fmt.Errorf("couldn't initialize media: %v", err)
|
return fmt.Errorf("couldn't initialize media: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
err = writeThemeFiles(ch.Dir)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println("error installing theme files:", err)
|
||||||
|
}
|
||||||
|
|
||||||
err = ch.Publish()
|
err = ch.Publish()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println("error with initial publish of hugo site:", err)
|
fmt.Println("error with initial publish of hugo site:", err)
|
||||||
|
|||||||
+22
-432
@@ -1,17 +1,19 @@
|
|||||||
package caddyhugo
|
package caddyhugo
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"html/template"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
"git.stephensearles.com/stephen/acedoc"
|
"git.stephensearles.com/stephen/acedoc"
|
||||||
|
"git.stephensearles.com/stephen/caddy-hugo2/frontend"
|
||||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func (t *tmplData) Content() ([]Content, error) {
|
func (t *tmplData) Content() ([]Content, error) {
|
||||||
@@ -63,7 +65,7 @@ func (t *tmplData) contentTypes(dir string) ([]string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type tmplData struct {
|
type tmplData struct {
|
||||||
Site *httpserver.SiteConfig
|
Site SiteConfig
|
||||||
R *http.Request
|
R *http.Request
|
||||||
*CaddyHugo
|
*CaddyHugo
|
||||||
Doc *acedoc.Document
|
Doc *acedoc.Document
|
||||||
@@ -88,441 +90,29 @@ func (t *tmplData) IframeSource() string {
|
|||||||
return fmt.Sprintf("/hugo/draft/%s/%s/%s/", base64.RawURLEncoding.EncodeToString([]byte(t.docref.docname)), ctype, strings.Replace(name, " ", "-", -1))
|
return fmt.Sprintf("/hugo/draft/%s/%s/%s/", base64.RawURLEncoding.EncodeToString([]byte(t.docref.docname)), ctype, strings.Replace(name, " ", "-", -1))
|
||||||
}
|
}
|
||||||
|
|
||||||
var EditPage = `<html>
|
var EditPage = frontend.EditPage()
|
||||||
<head>
|
|
||||||
<script src="/hugo/simplemde.js"></script>
|
|
||||||
<style type="text/css" media="screen">
|
|
||||||
#editor-wrapper {
|
|
||||||
position: absolute;
|
|
||||||
top: 50px;
|
|
||||||
right: 0;
|
|
||||||
bottom: 150px;
|
|
||||||
left: 40%;
|
|
||||||
}
|
|
||||||
#draft {
|
|
||||||
position: absolute;
|
|
||||||
top: 50px;
|
|
||||||
right: 60%;
|
|
||||||
bottom: 0;
|
|
||||||
left: 0;
|
|
||||||
|
|
||||||
}
|
var AdminPage = frontend.AdminPage()
|
||||||
#draft > iframe {
|
|
||||||
height: 100%;
|
|
||||||
width: 100%;
|
|
||||||
border: none;
|
|
||||||
}
|
|
||||||
a {
|
|
||||||
text-decoration: underline;
|
|
||||||
text-decoration-style: dotted;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
<link rel="stylesheet" href="/hugo/simplemde.css" />
|
|
||||||
<script src="/hugo/vue.js"></script>
|
|
||||||
<script src="/hugo/moment.js"></script>
|
|
||||||
|
|
||||||
|
var AuthorPage = frontend.AuthorPage()
|
||||||
|
|
||||||
<body>
|
var uploadTmpl *template.Template
|
||||||
<div id="container" >
|
var uploadTmplOnce sync.Once
|
||||||
<div id="header">
|
|
||||||
<div id="lastSaved">
|
|
||||||
<span v-if="sendQueue.length > 0 || Object.keys(needConfirmation).length > 0">last saved ${ lastSaved.from(now) }, saving</span>
|
|
||||||
<span v-else>saved</span>
|
|
||||||
<span v-if="connectionError">, ${connectionError}</span>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<a id="sideview-toggle-media">media</a>
|
|
||||||
<a id="sideview-toggle-draft">draft</a>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div id="editor-wrapper">
|
|
||||||
<textarea id="editor">{{ .LoadContent }}</textarea>
|
|
||||||
</div>
|
|
||||||
<div id="draft"><iframe src="{{ .IframeSource }}">Loading draft...</iframe></div>
|
|
||||||
</div>
|
|
||||||
<script>
|
|
||||||
|
|
||||||
var iframe = document.querySelector("#draft > iframe");
|
|
||||||
|
|
||||||
document.onclick = function (event) {
|
|
||||||
var iframe = document.querySelector("#draft > iframe");
|
|
||||||
switch (event.target.id) {
|
|
||||||
case "sideview-toggle-media":
|
|
||||||
iframe.src = "/hugo/media";
|
|
||||||
break;
|
|
||||||
case "sideview-toggle-draft":
|
|
||||||
iframe.src = "{{ .IframeSource }}";
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var uiBindings = {
|
|
||||||
ltime: {{ .LTime }},
|
|
||||||
serverLtime: 0,
|
|
||||||
lastSaved: moment(),
|
|
||||||
now: moment(),
|
|
||||||
connectionError: null,
|
|
||||||
sendQueue: [],
|
|
||||||
sentRecently: [],
|
|
||||||
needConfirmation: {},
|
|
||||||
};
|
|
||||||
|
|
||||||
var app = new Vue({
|
|
||||||
el: "#container",
|
|
||||||
data: uiBindings,
|
|
||||||
delimiters: ["${", "}"],
|
|
||||||
});
|
|
||||||
|
|
||||||
function getLtime() {
|
|
||||||
uiBindings.ltime++
|
|
||||||
return uiBindings.ltime
|
|
||||||
}
|
|
||||||
|
|
||||||
function observeServer(l, confirmed) {
|
|
||||||
uiBindings.serverLtime = l;
|
|
||||||
if (confirmed && confirmed.length > 0) {
|
|
||||||
confirmed.forEach(function (e) {
|
|
||||||
delete uiBindings.needConfirmation[e];
|
|
||||||
})
|
|
||||||
}
|
|
||||||
observe(l);
|
|
||||||
}
|
|
||||||
|
|
||||||
function observe(l) {
|
|
||||||
if (l > uiBindings.ltime) {
|
|
||||||
uiBindings.now = moment();
|
|
||||||
uiBindings.lastSaved = moment();
|
|
||||||
uiBindings.ltime = l;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var selectedImage;
|
|
||||||
var editorElem = document.getElementById("editor");
|
|
||||||
var editor = new SimpleMDE({
|
|
||||||
element: editorElem,
|
|
||||||
forceSync: true,
|
|
||||||
insertTexts: {
|
|
||||||
image: ["{\{% thumb filename=\"", "#url#\" width=\"200\" %}}"]
|
|
||||||
},
|
|
||||||
imageURLFn: function () {
|
|
||||||
return selectedImage;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
window.onmessage = function (evt) {
|
|
||||||
selectedImage = evt.data;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Create WebSocket connection.
|
|
||||||
var socket = connect();
|
|
||||||
|
|
||||||
|
|
||||||
const sawChangesBumpsTo = 10;
|
|
||||||
|
|
||||||
var sentinelSrc = 'about:blank';
|
|
||||||
var oldSrc = '';
|
|
||||||
|
|
||||||
var sawChanges = -1;
|
|
||||||
window.setInterval(function () {
|
|
||||||
if (sawChanges >= 0) {
|
|
||||||
sawChanges--;
|
|
||||||
if (sawChanges == 0) {
|
|
||||||
if (iframe.contentWindow) {
|
|
||||||
iframe.contentWindow.location.reload();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
uiBindings.now = moment();
|
|
||||||
if (uiBindings.connectionError) {
|
|
||||||
socket = connect();
|
|
||||||
} else if (uiBindings.sendQueue.length > 0) {
|
|
||||||
var ltime = getLtime();
|
|
||||||
|
|
||||||
// record lowest pending
|
|
||||||
// ltime at the time this message
|
|
||||||
// was serialized
|
|
||||||
var lowestPending = ltime;
|
|
||||||
for (c in uiBindings.needConfirmation) {
|
|
||||||
c = parseInt(c, 10);
|
|
||||||
if (lowestPending === 0 || c < lowestPending) {
|
|
||||||
lowestPending = c;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var msg = JSON.stringify({
|
|
||||||
"deltas": uiBindings.sendQueue,
|
|
||||||
"ltime": ltime,
|
|
||||||
"lowestPending": lowestPending,
|
|
||||||
});
|
|
||||||
uiBindings.sendQueue = [];
|
|
||||||
uiBindings.needConfirmation[ltime] = msg;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (ltime in uiBindings.needConfirmation) {
|
|
||||||
var msg = uiBindings.needConfirmation[ltime];
|
|
||||||
socket.send(msg);
|
|
||||||
}
|
|
||||||
}, 500);
|
|
||||||
|
|
||||||
function connect() {
|
|
||||||
const socket = new WebSocket((location.protocol == "https:" ? 'wss://' : 'ws://') + location.host + location.pathname);
|
|
||||||
|
|
||||||
// Listen for messages
|
|
||||||
socket.addEventListener('message', function (event) {
|
|
||||||
var message = JSON.parse(event.data);
|
|
||||||
observeServer(message.ltime, message.confirmed);
|
|
||||||
|
|
||||||
var deltas = [];
|
|
||||||
deltas.push.apply(deltas, message.deltas);
|
|
||||||
|
|
||||||
deltas.forEach(function(aceDelta) {
|
|
||||||
var cmDelta = aceDeltaToCM(aceDelta)
|
|
||||||
|
|
||||||
var content = ""
|
|
||||||
var to = {
|
|
||||||
line: aceDelta.start.row,
|
|
||||||
ch: aceDelta.start.column,
|
|
||||||
}
|
|
||||||
|
|
||||||
if (aceDelta.action == "insert") {
|
|
||||||
content = aceDelta.lines.join("\n");
|
|
||||||
to = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
editor.codemirror.doc.replaceRange(content, cmDelta.from, to, "dontreflect");
|
|
||||||
sawChanges = sawChangesBumpsTo;
|
|
||||||
})
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.addEventListener('open', function () {
|
|
||||||
uiBindings.connectionError = null;
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.addEventListener('close', function () {
|
|
||||||
if (!uiBindings.connectionError) {
|
|
||||||
getLtime();
|
|
||||||
uiBindings.connectionError = "server connection closed, reconnecting...";
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.addEventListener('error', function (err) {
|
|
||||||
if (!uiBindings.connectionError) {
|
|
||||||
uiBindings.connectionError = err;
|
|
||||||
getLtime();
|
|
||||||
}
|
|
||||||
console.log(err);
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
return socket;
|
|
||||||
}
|
|
||||||
|
|
||||||
editor.codemirror.on("change", function (cm, cmDelta) {
|
|
||||||
if (cmDelta.origin == "dontreflect") {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
var aceDelta = cmDeltaToAce(cmDelta);
|
|
||||||
console.log(cmDelta, "=>", aceDelta)
|
|
||||||
|
|
||||||
sawChanges = sawChangesBumpsTo;
|
|
||||||
uiBindings.sendQueue.push.apply(uiBindings.sendQueue, aceDelta);
|
|
||||||
})
|
|
||||||
|
|
||||||
function cmDeltaToAce(cmDelta) {
|
|
||||||
var isRemove = (cmDelta.removed.length > 0 && cmDelta.removed[0].length > 0) || cmDelta.removed.length > 1;
|
|
||||||
var lines = isRemove ? cmDelta.removed : cmDelta.text;
|
|
||||||
var aceDelta = {
|
|
||||||
action: isRemove ? "remove" : "insert",
|
|
||||||
lines: lines,
|
|
||||||
start: {
|
|
||||||
row: cmDelta.from.line,
|
|
||||||
column: cmDelta.from.ch,
|
|
||||||
},
|
|
||||||
end: {
|
|
||||||
row: cmDelta.from.line + (isRemove ? lines.length - 1 : lines.length - 1 ),
|
|
||||||
column: lines[lines.length-1].length,
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if (aceDelta.start.row == aceDelta.end.row) {
|
|
||||||
aceDelta.end.column += cmDelta.from.ch;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (false && isRemove && aceDelta.start.row == aceDelta.end.row) {
|
|
||||||
var origStart = aceDelta.start;
|
|
||||||
aceDelta.start = aceDelta.end;
|
|
||||||
aceDelta.end = origStart;
|
|
||||||
aceDelta.start.column += cmDelta.from.ch;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isRemove && ((cmDelta.text.length > 0 && cmDelta.text[0].length > 0) || cmDelta.text.length > 1)) {
|
|
||||||
cmDelta.removed = [""];
|
|
||||||
var ret = [aceDelta];
|
|
||||||
ret.push.apply(ret, cmDeltaToAce(cmDelta));
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
return [aceDelta];
|
|
||||||
}
|
|
||||||
|
|
||||||
function aceDeltaToCM(aceDelta) {
|
|
||||||
|
|
||||||
var cmDelta = {
|
|
||||||
text: [],
|
|
||||||
removed: [],
|
|
||||||
from: {
|
|
||||||
line: aceDelta.start.row,
|
|
||||||
ch: aceDelta.start.column,
|
|
||||||
},
|
|
||||||
to: {
|
|
||||||
// cm deltas are weird. to refers to the selection end, which
|
|
||||||
// with a simple blinking cursor with no selection, is always
|
|
||||||
// the same as from
|
|
||||||
line: aceDelta.start.row,
|
|
||||||
ch: aceDelta.start.column,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
if (aceDelta.action == "remove") {
|
|
||||||
var origStart = aceDelta.start;
|
|
||||||
aceDelta.start = aceDelta.end;
|
|
||||||
aceDelta.end = origStart;
|
|
||||||
|
|
||||||
cmDelta.removed = aceDelta.lines
|
|
||||||
cmDelta.text = [""]
|
|
||||||
} else {
|
|
||||||
cmDelta.text = aceDelta.lines
|
|
||||||
cmDelta.removed = [""]
|
|
||||||
}
|
|
||||||
|
|
||||||
return cmDelta;
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
</body>
|
|
||||||
</html>`
|
|
||||||
|
|
||||||
var AdminPage = `<html><body>not implemented</body></html>`
|
|
||||||
|
|
||||||
var AuthorPage = `<html>
|
|
||||||
<head>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
{{ $timeFormat := "Jan _2 15:04:05" }}
|
|
||||||
<p>Create content:</p>
|
|
||||||
<form action="/hugo/edit/new" method="POST">
|
|
||||||
<label>Name: <input type="text" name="name" /></label>
|
|
||||||
<select name="type">
|
|
||||||
{{- range .ContentTypes }}
|
|
||||||
<option value="{{ . }}">{{ . }}</option>
|
|
||||||
{{- end }}
|
|
||||||
</select>
|
|
||||||
<input type="submit" />
|
|
||||||
</form>
|
|
||||||
|
|
||||||
<p>Edit content:</p>
|
|
||||||
<table>{{ range .Content }}
|
|
||||||
<tr>
|
|
||||||
{{ if .Metadata }}
|
|
||||||
<td>
|
|
||||||
<a href="/hugo/edit/{{ .Filename }}">
|
|
||||||
{{ .Metadata.Title }}
|
|
||||||
</a>
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
{{ .Metadata.Date.Format $timeFormat }}
|
|
||||||
{{ if not (.Metadata.Lastmod.Equal .Metadata.Date) }}
|
|
||||||
(last modified {{.Metadata.Lastmod.Format $timeFormat }})
|
|
||||||
{{end}}
|
|
||||||
</td>
|
|
||||||
{{ else }}
|
|
||||||
<td>
|
|
||||||
<a href="/hugo/edit/{{ .Filename }}">
|
|
||||||
{{ .Filename }}
|
|
||||||
</a>
|
|
||||||
</td>
|
|
||||||
<td>(unable to load metadata)</td>
|
|
||||||
{{ end }}
|
|
||||||
</tr>
|
|
||||||
{{- end }}
|
|
||||||
</table>
|
|
||||||
</body>
|
|
||||||
</html>`
|
|
||||||
|
|
||||||
func UploadPage(elemName string) string {
|
func UploadPage(elemName string) string {
|
||||||
return fmt.Sprintf(`
|
uploadTmplOnce.Do(func() {
|
||||||
<input type="file" style="display: hidden;" id="%s" />
|
p := frontend.UploadPage()
|
||||||
<div id="%s_dropzone" ondrop="dropHandler(event);" ondragover="draghandler(event);" ondragenter="draghandler(event);" ondragleave="draghandler(event);" style="background-color: rgba(0,0,0,0.5); visibility: hidden; opacity:0; position: fixed; top: 0; bottom: 0; left: 0; right: 0; width: 100%; height: 100%; ; transition: visibility 175ms, opacity 175ms; z-index: 9999999;"></div>
|
t, err := template.New("").Parse(p)
|
||||||
<script>
|
if err != nil {
|
||||||
document.addEventListener("DOMContentLoaded", function () {
|
panic(err)
|
||||||
var fileInput = document.getElementById('%s');
|
|
||||||
var dropzone = document.getElementById('%s_dropzone');
|
|
||||||
|
|
||||||
fileInput.onchange = function () {
|
|
||||||
var formData = new FormData();
|
|
||||||
fileInput.files.forEach(function (file) {
|
|
||||||
formData.append(file.name, file);
|
|
||||||
});
|
|
||||||
upload(formData);
|
|
||||||
}
|
|
||||||
|
|
||||||
var lastTarget = null;
|
|
||||||
|
|
||||||
window.addEventListener("dragenter", function(e)
|
|
||||||
{
|
|
||||||
lastTarget = e.target; // cache the last target here
|
|
||||||
// unhide our dropzone overlay
|
|
||||||
dropzone.style.visibility = "";
|
|
||||||
dropzone.style.opacity = 1;
|
|
||||||
});
|
|
||||||
|
|
||||||
window.addEventListener("dragleave", function(e)
|
|
||||||
{
|
|
||||||
// this is the magic part. when leaving the window,
|
|
||||||
// e.target happens to be exactly what we want: what we cached
|
|
||||||
// at the start, the dropzone we dragged into.
|
|
||||||
// so..if dragleave target matches our cache, we hide the dropzone.
|
|
||||||
if(e.target === lastTarget)
|
|
||||||
{
|
|
||||||
dropzone.style.visibility = "hidden";
|
|
||||||
dropzone.style.opacity = 0;
|
|
||||||
}
|
}
|
||||||
});
|
uploadTmpl = t
|
||||||
|
})
|
||||||
|
|
||||||
});
|
var buf bytes.Buffer
|
||||||
|
err := uploadTmpl.Execute(&buf, struct{ ElemName string }{elemName})
|
||||||
function draghandler(evt) {
|
if err != nil {
|
||||||
evt.preventDefault();
|
panic(err)
|
||||||
}
|
}
|
||||||
|
return buf.String()
|
||||||
function dropHandler(evt) {
|
|
||||||
evt.preventDefault();
|
|
||||||
|
|
||||||
var files = evt.dataTransfer.files;
|
|
||||||
var formData = new FormData();
|
|
||||||
|
|
||||||
for (var i = 0; i < files.length; i++) {
|
|
||||||
formData.append(files[i].name, files[i]);
|
|
||||||
}
|
|
||||||
|
|
||||||
upload(formData);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
function upload(formData) {
|
|
||||||
var xhr = new XMLHttpRequest();
|
|
||||||
xhr.onreadystatechange = function(e) {
|
|
||||||
if ( 4 == this.readyState ) {
|
|
||||||
window.location.reload(true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
xhr.open('POST', '/hugo/upload');
|
|
||||||
xhr.send(formData);
|
|
||||||
}
|
|
||||||
|
|
||||||
</script>
|
|
||||||
`, elemName, elemName, elemName, elemName, elemName, elemName)
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
order hugo last
|
||||||
|
}
|
||||||
|
|
||||||
|
http://localhost:8080 {
|
||||||
|
hugo {
|
||||||
|
comments test
|
||||||
|
}
|
||||||
|
root ./testdir/testsite
|
||||||
|
log
|
||||||
|
}
|
||||||
|
|
||||||
|
http://localhost:8081, http://localhost:8082 {
|
||||||
|
root ./testdir/testsite2
|
||||||
|
hugo
|
||||||
|
log
|
||||||
|
}
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
localhost:8080 {
|
|
||||||
hugo {
|
|
||||||
comments test
|
|
||||||
}
|
|
||||||
root ./testsite
|
|
||||||
errors { * }
|
|
||||||
pprof
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
baseURL = "http://example.org/"
|
baseURL = "http://example.org/"
|
||||||
languageCode = "en-us"
|
languageCode = "en-us"
|
||||||
title = "My New Hugo Site"
|
title = "My New Hugo Site"
|
||||||
theme = "hugo-theme-minos"
|
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
baseURL = "http://example.org/"
|
||||||
|
languageCode = "en-us"
|
||||||
|
title = "My New Hugo Site"
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
|
||||||
|
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
|
||||||
|
<channel>
|
||||||
|
<title>Categories on My New Hugo Site</title>
|
||||||
|
<link>http://example.org/categories/</link>
|
||||||
|
<description>Recent content in Categories on My New Hugo Site</description>
|
||||||
|
<generator>Hugo -- gohugo.io</generator>
|
||||||
|
<language>en-us</language>
|
||||||
|
|
||||||
|
<atom:link href="http://example.org/categories/index.xml" rel="self" type="application/rss+xml" />
|
||||||
|
|
||||||
|
|
||||||
|
</channel>
|
||||||
|
</rss>
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
|
||||||
|
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
|
||||||
|
<channel>
|
||||||
|
<title>My New Hugo Site</title>
|
||||||
|
<link>http://example.org/</link>
|
||||||
|
<description>Recent content on My New Hugo Site</description>
|
||||||
|
<generator>Hugo -- gohugo.io</generator>
|
||||||
|
<language>en-us</language>
|
||||||
|
|
||||||
|
<atom:link href="http://example.org/index.xml" rel="self" type="application/rss+xml" />
|
||||||
|
|
||||||
|
|
||||||
|
</channel>
|
||||||
|
</rss>
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
|
||||||
|
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
|
||||||
|
xmlns:xhtml="http://www.w3.org/1999/xhtml">
|
||||||
|
|
||||||
|
<url>
|
||||||
|
<loc>http://example.org/categories/</loc>
|
||||||
|
<priority>0</priority>
|
||||||
|
</url>
|
||||||
|
|
||||||
|
<url>
|
||||||
|
<loc>http://example.org/</loc>
|
||||||
|
<priority>0</priority>
|
||||||
|
</url>
|
||||||
|
|
||||||
|
<url>
|
||||||
|
<loc>http://example.org/tags/</loc>
|
||||||
|
<priority>0</priority>
|
||||||
|
</url>
|
||||||
|
|
||||||
|
</urlset>
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
|
||||||
|
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
|
||||||
|
<channel>
|
||||||
|
<title>Tags on My New Hugo Site</title>
|
||||||
|
<link>http://example.org/tags/</link>
|
||||||
|
<description>Recent content in Tags on My New Hugo Site</description>
|
||||||
|
<generator>Hugo -- gohugo.io</generator>
|
||||||
|
<language>en-us</language>
|
||||||
|
|
||||||
|
<atom:link href="http://example.org/tags/index.xml" rel="self" type="application/rss+xml" />
|
||||||
|
|
||||||
|
|
||||||
|
</channel>
|
||||||
|
</rss>
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
+++
|
||||||
|
title = ""
|
||||||
|
tags = [
|
||||||
|
"gallery"
|
||||||
|
]
|
||||||
|
categories = [
|
||||||
|
"gallery"
|
||||||
|
]
|
||||||
|
draft = true
|
||||||
|
|
||||||
|
[photos]
|
||||||
|
"/media/IMG000.png" = "a great photo"
|
||||||
|
"/media/IMG003.png" = ""
|
||||||
|
|
||||||
|
+++
|
||||||
|
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
//go:generate go-bindata -ignore .go -pkg themeadditions ./...
|
||||||
|
|
||||||
|
package themeadditions
|
||||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,15 @@
|
|||||||
|
{{ partial "head.html" . }}
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<div id="container">
|
||||||
|
{{ partial "header.html" . }}
|
||||||
|
<section id="main" class="outer">
|
||||||
|
{{ partial "gallery.html" . }}
|
||||||
|
{{ if and (not .Params.nocomment) .Site.Params.disqusShortname }}
|
||||||
|
{{ template "_internal/disqus.html" . }}
|
||||||
|
{{ end }}
|
||||||
|
</section>
|
||||||
|
{{ partial "footer.html" . }}
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
<style>
|
||||||
|
figure {
|
||||||
|
text-align: center;
|
||||||
|
float: left;
|
||||||
|
margin: 0;
|
||||||
|
max-width: 100%;
|
||||||
|
transition-property: height min-height scale;
|
||||||
|
transition-duration: 1s;
|
||||||
|
}
|
||||||
|
.floatclear {
|
||||||
|
clear: both;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
<article class="article article-type-post" itemscope itemprop="blogPost">
|
||||||
|
<div class="article-inner">
|
||||||
|
{{ if .Title }}
|
||||||
|
<header class="article-header">
|
||||||
|
<h1 class="article-title" itemprop="name">{{ .Title }}</h1>
|
||||||
|
</header>
|
||||||
|
{{ end }}
|
||||||
|
<div class="article-meta">
|
||||||
|
<a href="{{ .RelPermalink }}" class="article-date">
|
||||||
|
<time datetime='{{ .Date.Format "2006-01-02T15:04:05.000-07:00" }}' itemprop="datePublished">{{ .Date.Format "2006-01-02" }}</time>
|
||||||
|
</a>
|
||||||
|
{{ $Site := .Site }}
|
||||||
|
{{ if .Params.categories }}
|
||||||
|
<div class="post-categories">
|
||||||
|
<div class="article-category">
|
||||||
|
{{ range $i, $e := .Params.categories }}
|
||||||
|
{{ if gt $i 0 }}
|
||||||
|
<span>></span>
|
||||||
|
{{ end }}
|
||||||
|
<a class="article-category-link" href="{{ $Site.BaseURL }}/categories/{{ $e | urlize }}">{{ $e }}</a>
|
||||||
|
{{ end }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{{ end }}
|
||||||
|
{{ if .Site.Params.disqusShortname }}
|
||||||
|
<div class="article-comment-link-wrap">
|
||||||
|
<a href="{{ .RelPermalink }}#disqus_thread" class="article-comment-link">Comments</a>
|
||||||
|
</div>
|
||||||
|
{{ end }}
|
||||||
|
</div>
|
||||||
|
<div class="article-entry" itemprop="articleBody">
|
||||||
|
{{ range $i, $_ := .Params.photos }}
|
||||||
|
{{ $splitnum := split .url "/" | len | add -1}}
|
||||||
|
{{ $name := index (split .url "/") $splitnum }}
|
||||||
|
{{ if not $i }}
|
||||||
|
<figure class="image" id="full-figure" >
|
||||||
|
<img src="/media/{{ $name }}" id="{{$name}}" {{ with .alt }}alt="{{ . }}"{{ end }} data-caption="{{.caption}}"/>
|
||||||
|
<figcaption>{{ with .caption }}{{ . }}{{ end }}</figcaption>
|
||||||
|
</figure>
|
||||||
|
<div class="floatclear"></div>
|
||||||
|
{{ end }}
|
||||||
|
|
||||||
|
<figure class="thumb" >
|
||||||
|
<img src="/media/x100/{{ $name }}" id="{{$name}}" alt="{{ with .alt }}{{ . }}{{ else }}{{ .caption }}{{ end }}" data-name="{{$name}}" data-caption="{{.caption}}"/>
|
||||||
|
</figure>
|
||||||
|
{{ end }}
|
||||||
|
<div class="floatclear"></div>
|
||||||
|
{{ .Content }}
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
function getElementIndex(node) {
|
||||||
|
var index = 0;
|
||||||
|
while ( (node = node.previousElementSibling) ) {
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
|
||||||
|
var image = document.querySelector("figure.image").firstElementChild;
|
||||||
|
image.parentElement.style.minHeight = image.scrollHeight + "px";
|
||||||
|
|
||||||
|
image.onload = function () {
|
||||||
|
image.parentElement.style.minHeight = '';
|
||||||
|
};
|
||||||
|
|
||||||
|
document.querySelector(".article-entry").onclick = function (evt) {
|
||||||
|
if (evt.target.tagName === "IMG" && evt.target.parentElement.className === "thumb") {
|
||||||
|
image.src = ""
|
||||||
|
image.src = "/media/" + evt.target.dataset.name;
|
||||||
|
image.nextElementSibling.innerText = evt.target.dataset.caption;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{{ if not .Params.notoc }}
|
||||||
|
{{ if .TableOfContents }}
|
||||||
|
<div class="article-toc" {{ if .Site.Params.SmartToc }}style="display:none;"{{ end }}>
|
||||||
|
<h3>Contents</h3>
|
||||||
|
{{ .TableOfContents }}
|
||||||
|
</div>
|
||||||
|
{{ end }}
|
||||||
|
{{ end }}
|
||||||
|
|
||||||
|
{{ if .Site.Params.SmartToc }}
|
||||||
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.slim.min.js" integrity="sha256-/SIrNqv8h6QGKDuNoLGA4iret+kyesCkHGzVUUV0shc=" crossorigin="anonymous"></script>
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var $toc = $('#TableOfContents');
|
||||||
|
if ($toc.length > 0) {
|
||||||
|
var $window = $(window);
|
||||||
|
|
||||||
|
function onScroll(){
|
||||||
|
var currentScroll = $window.scrollTop();
|
||||||
|
var h = $('.article-entry h1, .article-entry h2, .article-entry h3, .article-entry h4, .article-entry h5, .article-entry h6');
|
||||||
|
var id = "";
|
||||||
|
h.each(function (i, e) {
|
||||||
|
e = $(e);
|
||||||
|
if (e.offset().top - 10 <= currentScroll) {
|
||||||
|
id = e.attr('id');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
var active = $toc.find('a.active');
|
||||||
|
if (active.length == 1 && active.eq(0).attr('href') == '#' + id) return true;
|
||||||
|
|
||||||
|
active.each(function (i, e) {
|
||||||
|
$(e).removeClass('active').siblings('ul').hide();
|
||||||
|
});
|
||||||
|
$toc.find('a[href="#' + id + '"]').parentsUntil('#TableOfContents').each(function (i, e) {
|
||||||
|
$(e).children('a').addClass('active').siblings('ul').show();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
$window.on('scroll', onScroll);
|
||||||
|
$(document).ready(function() {
|
||||||
|
$toc.find('a').parent('li').find('ul').hide();
|
||||||
|
onScroll();
|
||||||
|
document.getElementsByClassName('article-toc')[0].style.display = '';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
{{ end }}
|
||||||
|
|
||||||
|
|
||||||
|
{{ if .Params.tags }}
|
||||||
|
<footer class="article-footer">
|
||||||
|
<ul class="article-tag-list">
|
||||||
|
{{ range .Params.tags }}
|
||||||
|
<li class="article-tag-list-item">
|
||||||
|
<a class="article-tag-list-link" href="{{ $Site.BaseURL}}/tags/{{ . | urlize }}">{{ . }}
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
{{ end }}
|
||||||
|
</ul>
|
||||||
|
</footer>
|
||||||
|
{{ end }}
|
||||||
|
</div>
|
||||||
|
{{ partial "nav.html" . }}
|
||||||
|
</article>
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
<script>
|
||||||
|
window.onload = function () {
|
||||||
|
refreshComments();
|
||||||
|
};
|
||||||
|
|
||||||
|
function refreshComments() {
|
||||||
|
var xhr = new XMLHttpRequest();
|
||||||
|
xhr.open("GET", "./comments");
|
||||||
|
xhr.onload = function () {
|
||||||
|
document.querySelector("#comments").innerHTML = xhr.responseText;
|
||||||
|
};
|
||||||
|
xhr.send();
|
||||||
|
}
|
||||||
|
|
||||||
|
window.submitComment = function (evt) {
|
||||||
|
evt.preventDefault();
|
||||||
|
var xhr = new XMLHttpRequest();
|
||||||
|
xhr.open('POST', './comments', true);
|
||||||
|
xhr.send(JSON.stringify({"text": evt.target.querySelector('textarea').value}));
|
||||||
|
xhr.onload = function () {
|
||||||
|
refreshComments();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
<div id="comments"></div>
|
||||||
|
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
{{ $filename := .Get "filename" -}}
|
||||||
|
{{ $ext := substr $filename (sub (len $filename) 4) }}
|
||||||
|
<p
|
||||||
|
{{ if eq (.Get "align") "left" }}class="leftimg"{{else if (.Get "align") "right"}}class="rightimg"{{end }}>
|
||||||
|
{{ if eq $ext ".mp4" }}
|
||||||
|
<video src="/media/
|
||||||
|
{{- with .Get "width"}}{{.}}{{else}}100{{end}}x{{with .Get "height"}}{{.}}{{else}}{{end}}/{{ $filename -}}"
|
||||||
|
controls allowfullscreen
|
||||||
|
></video>
|
||||||
|
{{ else }}
|
||||||
|
<a href="/media/{{ $filename }}" target="_blank"><img src="/media/
|
||||||
|
{{- with .Get "width"}}{{.}}{{else}}100{{end}}x{{with .Get "height"}}{{.}}{{else}}{{end}}/{{ $filename -}}"
|
||||||
|
{{ with .Get "caption" }}title="{{.}}"{{end}}
|
||||||
|
{{ with .Get "caption" }}alt="{{.}}"{{end}}
|
||||||
|
/></a>
|
||||||
|
{{end}}
|
||||||
|
</p>
|
||||||
Reference in New Issue
Block a user