<commit_before>/*
   Copyright 2012 <NAME>

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package bootstrap.liftweb

import net.liftweb._
import common._
import util._
import http._
import mongodb.{DefaultMongoIdentifier, MongoDB}
import http.auth._
import sitemap._
import Loc._
import util.Helpers._
import sitemap.LocPath._
import daemon.sshd.SshDaemon
import actors.Actor
import xml.{NodeSeq, Text}
import daemon.git.GitDaemon
import com.mongodb.Mongo
import code.model._

trait WithUser {
  def userName: String

  lazy val user = UserDoc.find("login", userName)
}

case class UserPage(userName: String) extends WithUser

trait WithRepo extends WithUser {
  def repoName: String

  lazy val repo = user match {

    case Full(u) => (tryo {  u.repos.filter(_.name.get == repoName).head } or { Empty }) match {
      case Full(r) if (r.open_?.get) => Full(r)
      case Full(r) if (r.canPush_?(UserDoc.currentUser)) => Full(r)
      case _ => Empty
    }
        
    case _ => Empty
  }
}

trait WithPullRequest {
  def pullRequestId: String

  lazy val pullRequest = PullRequestDoc.find(pullRequestId)
}

trait WithCommit extends WithRepo {
  def commit: String
}

case class RepoPage(userName: String, repoName: String) extends WithRepo

case class RepoAtCommitPage(userName: String, repoName: String, commit: String) extends WithCommit

case class PullRequestRepoPage(userName: String, repoName: String, pullRequestId: String)  extends WithPullRequest with WithRepo

case class SourceElementPage(userName: String, repoName: String, commit: String, path: List[String]) extends WithCommit {
  
  private lazy val reversedPath = path.reverse

  lazy val elem = repo.flatMap(r => tryo { r.git.ls_tree(reversedPath.tail.reverse, commit).filter(_.basename == reversedPath.head).head } or {Empty})
}




/**
 * A class that's instantiated early and run.  It allows the application
 * to modify lift's environment
 */
class Boot extends Loggable {
  def boot {
    val dbHost = Props.get("db.host", "localhost")
    val dbPort = Props.getInt("db.port", 27017)
    val dbName = Props.get("db.name", "grt")

    Props.get("db.user") match {
      case Full(userName) => {
        Props.requireOrDie("db.password")
        MongoDB.defineDbAuth(DefaultMongoIdentifier, new Mongo(dbHost, dbPort), dbName, userName, Props.get("db.password").get)
      }
      case _ => 
        MongoDB.defineDb(DefaultMongoIdentifier, new Mongo(dbHost, dbPort), dbName)
    }

    try { 
      SshDaemon.init
    } catch {
      case e => logger.warn("Exception while start sshd", e)
    }
    try { 
      GitDaemon.init
    } catch {
      case e => logger.warn("Exception while start gitd", e)
    }

    LiftRules.unloadHooks.append(
      () => {
        SshDaemon.shutdown
        GitDaemon.shutdown
        notification.client.NotifyActor.onShutdown
      }
    )

    // where to search snippet
    LiftRules.addToPackages("code")

    LiftRules.explicitlyParsedSuffixes = Set()

    val indexPage = Menu.i("Home") / "index" >> If(() => !UserDoc.loggedIn_?, () => RedirectResponse(UserDoc.currentUser.get.homePageUrl))
    // val listPage = Menu.i("List") / "list"

    val userPage = Menu.param[UserPage]("userPage",
      new LinkText[UserPage](up => Text("User " + up.userName)),
      login => Full(UserPage(login)),
      up => up.userName) / "list" / * >>
      ValueTemplate(upBox => upBox.flatMap(up => up.user).flatMap(u => Templates("list" :: Nil))
          .openOr(Templates("404" :: Nil).openOr(NodeSeq.Empty)))

    val userAdminPage = Menu.param[UserPage]("userAdminPage",
      new LinkText[UserPage](up => Text("User " + up.userName)),
      login => Full(UserPage(login)),
      up => up.userName) / "admin" / *  >>
      ValueTemplate(upBox => upBox.flatMap(up => up.user)
        .filter(_.is(UserDoc.currentUser))
        .flatMap(u => Templates("admin" :: "adminUser" :: Nil))
          .openOr(Templates("404" :: Nil).openOr(NodeSeq.Empty)))
     

    val userRepoAdminPage = Menu.params[RepoPage]("userRepoAdminPage",
      new LinkText[RepoPage](urp => Text("Repo " + urp.repoName)),
      list => list match {
        case login :: repo :: Nil => Full(RepoPage(login, repo))
        case _ => Empty
      },
      urp => urp.userName :: urp.repoName :: Nil) / "admin" / * / * >>
      ValueTemplate(upBox => upBox.flatMap(up => up.user)
        .filter(_.is(UserDoc.currentUser))
        .flatMap(u => Templates("admin" :: "adminRepo" :: Nil))
          .openOr(Templates("404" :: Nil).openOr(NodeSeq.Empty)))

    val blobPage = Menu.params[SourceElementPage]("blobPage",
      new LinkText[SourceElementPage](stp => Text("Repo " + stp.repoName)),
      list => list match {
          case login :: repo :: commit :: path => Full(SourceElementPage(login, repo, commit, path))
          case _ => Empty
      },
      stp => (stp.userName :: stp.repoName :: stp.commit :: Nil) ::: stp.path) / * / * / "blob" / * / **  >>
      ValueTemplate(upBox =>
        upBox.flatMap(rp => rp.repo).filter(r => r.canPull_?(UserDoc.currentUser))
          .flatMap(r => Templates("repo" :: "blob" :: Nil))
          .openOr(Templates("404" :: Nil).openOr(NodeSeq.Empty)))
      

    val emptyRepoPage = Menu.params[SourceElementPage]("emptyRepoPage",
      new LinkText[SourceElementPage](stp => Text("Repo " + stp.repoName)),
      list => {

        list match {
          case login :: repo :: Nil => Full(SourceElementPage(login, repo, "", Nil))
          case _ => Empty
        }
      },
      stp => stp.userName :: stp.repoName :: Nil) / * / * / "tree" >>
      ValueTemplate(spBox =>
        spBox.flatMap(rp => rp.repo).filter(r => r.canPull_?(UserDoc.currentUser))
          .flatMap(r => Templates("repo" :: "tree" :: Nil))
          .openOr(Templates("404" :: Nil).openOr(NodeSeq.Empty))) >>
      TestValueAccess(_.flatMap(rp => rp.repo).filter(r => r.git.inited_?)<commit_msg>Show default page for not inited repos<commit_after>/*
   Copyright 2012 <NAME>

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package bootstrap.liftweb

import net.liftweb._
import common._
import util._
import http._
import mongodb.{DefaultMongoIdentifier, MongoDB}
import http.auth._
import sitemap._
import Loc._
import util.Helpers._
import sitemap.LocPath._
import daemon.sshd.SshDaemon
import actors.Actor
import xml.{NodeSeq, Text}
import daemon.git.GitDaemon
import com.mongodb.Mongo
import code.model._

trait WithUser {
  def userName: String

  lazy val user = UserDoc.find("login", userName)
}

case class UserPage(userName: String) extends WithUser

trait WithRepo extends WithUser {
  def repoName: String

  lazy val repo = user match {

    case Full(u) => (tryo {  u.repos.filter(_.name.get == repoName).head } or { Empty }) match {
      case Full(r) if (r.open_?.get) => Full(r)
      case Full(r) if (r.canPush_?(UserDoc.currentUser)) => Full(r)
      case _ => Empty
    }
        
    case _ => Empty
  }
}

trait WithPullRequest {
  def pullRequestId: String

  lazy val pullRequest = PullRequestDoc.find(pullRequestId)
}

trait WithCommit extends WithRepo {
  def commit: String
}

case class RepoPage(userName: String, repoName: String) extends WithRepo

case class RepoAtCommitPage(userName: String, repoName: String, commit: String) extends WithCommit

case class PullRequestRepoPage(userName: String, repoName: String, pullRequestId: String)  extends WithPullRequest with WithRepo

case class SourceElementPage(userName: String, repoName: String, commit: String, path: List[String]) extends WithCommit {
  
  private lazy val reversedPath = path.reverse

  lazy val elem = repo.flatMap(r => tryo { r.git.ls_tree(reversedPath.tail.reverse, commit).filter(_.basename == reversedPath.head).head } or {Empty})
}




/**
 * A class that's instantiated early and run.  It allows the application
 * to modify lift's environment
 */
class Boot extends Loggable {
  def boot {
    val dbHost = Props.get("db.host", "localhost")
    val dbPort = Props.getInt("db.port", 27017)
    val dbName = Props.get("db.name", "grt")

    Props.get("db.user") match {
      case Full(userName) => {
        Props.requireOrDie("db.password")
        MongoDB.defineDbAuth(DefaultMongoIdentifier, new Mongo(dbHost, dbPort), dbName, userName, Props.get("db.password").get)
      }
      case _ => 
        MongoDB.defineDb(DefaultMongoIdentifier, new Mongo(dbHost, dbPort), dbName)
    }

    try { 
      SshDaemon.init
    } catch {
      case e => logger.warn("Exception while start sshd", e)
    }
    try { 
      GitDaemon.init
    } catch {
      case e => logger.warn("Exception while start gitd", e)
    }

    LiftRules.unloadHooks.append(
      () => {
        SshDaemon.shutdown
        GitDaemon.shutdown
        notification.client.NotifyActor.onShutdown
      }
    )

    // where to search snippet
    LiftRules.addToPackages("code")

    LiftRules.explicitlyParsedSuffixes = Set()

    val indexPage = Menu.i("Home") / "index" >> If(() => !UserDoc.loggedIn_?, () => RedirectResponse(UserDoc.currentUser.get.homePageUrl))
    // val listPage = Menu.i("List") / "list"

    val userPage = Menu.param[UserPage]("userPage",
      new LinkText[UserPage](up => Text("User " + up.userName)),
      login => Full(UserPage(login)),
      up => up.userName) / "list" / * >>
      ValueTemplate(upBox => upBox.flatMap(up => up.user).flatMap(u => Templates("list" :: Nil))
          .openOr(Templates("404" :: Nil).openOr(NodeSeq.Empty)))

    val userAdminPage = Menu.param[UserPage]("userAdminPage",
      new LinkText[UserPage](up => Text("User " + up.userName)),
      login => Full(UserPage(login)),
      up => up.userName) / "admin" / *  >>
      ValueTemplate(upBox => upBox.flatMap(up => up.user)
        .filter(_.is(UserDoc.currentUser))
        .flatMap(u => Templates("admin" :: "adminUser" :: Nil))
          .openOr(Templates("404" :: Nil).openOr(NodeSeq.Empty)))
     

    val userRepoAdminPage = Menu.params[RepoPage]("userRepoAdminPage",
      new LinkText[RepoPage](urp => Text("Repo " + urp.repoName)),
      list => list match {
        case login :: repo :: Nil => Full(RepoPage(login, repo))
        case _ => Empty
      },
      urp => urp.userName :: urp.repoName :: Nil) / "admin" / * / * >>
      ValueTemplate(upBox => upBox.flatMap(up => up.user)
        .filter(_.is(UserDoc.currentUser))
        .flatMap(u => Templates("admin" :: "adminRepo" :: Nil))
          .openOr(Templates("404" :: Nil).openOr(NodeSeq.Empty)))

    val blobPage = Menu.params[SourceElementPage]("blobPage",
      new LinkText[SourceElementPage](stp => Text("Repo " + stp.repoName)),
      list => list match {
          case login :: repo :: commit :: path => Full(SourceElementPage(login, repo, commit, path))
          case _ => Empty
      },
      stp => (stp.userName :: stp.repoName :: stp.commit :: Nil) ::: stp.path) / * / * / "blob" / * / **  >>
      ValueTemplate(upBox =>
        upBox.flatMap(rp => rp.repo).filter(r => r.canPull_?(UserDoc.currentUser))
          .flatMap(r => Templates("repo" :: "blob" :: Nil))
          .openOr(Templates("404" :: Nil).openOr(NodeSeq.Empty)))
      

    val emptyRepoPage = Menu.params[SourceElementPage]("emptyRepoPage",
      new LinkText[SourceElementPage](stp => Text("Repo " + stp.repoName)),
      list => {

        list match {
          case login :: repo :: Nil => Full(SourceElementPage(login, repo, "", Nil))
          case _ => Empty
        }
      },
      stp => stp.userName :: stp.repoName :: Nil) / * / * / "tree" >>
      ValueTemplate(spBox =>
        spBox.flatMap(rp => rp.repo).filter(r => r.canPull_?(UserDoc.currentUser))
          .flatMap(r => Templates("repo" :: "default" :: Nil))
          .openOr(Templates("404" :: Nil).openOr(NodeSeq.Empty))) >>
      TestValueAccess(_.flatMap(rp => rp.repo).filter(r => r.git.inited_?)
{'fraction_non_alphanumeric': 0.13889321901792673, 'fraction_numerical': 0.00436477007014809, 'mean_word_length': 3.113818531580635, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 139, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3303086', 'n_tokens_mistral': 4183, 'n_tokens_neox': 4071, 'n_words': 971}